/**

 * All Widget depend on jQuery
 * 
 */
// Start of DateTimePicker
(function() {
	// Picker object
	var smartPhone = (window.orientation != undefined);
	var DateTimePicker = function(element, options) {
		this.ret = [];
		this.id = dpgId++;
		this.init(element, options);
	};

	var dateToDate = function(dt) {
		if (typeof dt === 'string') {
			return new Date(dt);
		}
		return dt;
	};

	DateTimePicker.prototype = {
		constructor: DateTimePicker,

		init : function(element, options) {
			var icon = $();
			// 优化配置
			options.pickDate = options.pickDate || options.pickMonth;		//如果配置了选择年月，则启动仅日期模式
			options.pickTime = options.pickTime && !options.pickMonth;		//如果配置了只选择年月，即时间不可用
			
			if (!(options.pickTime || options.pickDate))
				throw new Error('Must choose at least one picker');
			this.options = options;
			this.$element = $(element);
			this.position = $(element).attr('position') || 'bottom';
			this.language = options.language in dates ? options.language : 'zh-CN';
			this.pickDate = options.pickDate;		
			this.pickTime = options.pickTime;	
			this.pickMonth = false || options.pickMonth;	//新增配置，只选择年月
			this.manyDate = false || options.manyDate; //双面板日历 默认 false
			this.manyDateElem = '.many-date' || '';
			this.autoHide = false || options.autoHide;

			this.isInput = this.$element.is('input');
			this.component = false;
			this.changeFun = options.changeFun;
			if (this.$element.find('.input-append').length || this.$element.find('.input-prepend').length)
				this.component = this.$element.find('.add-on');
			this.format = options.format;
			if (!this.format) {
				if (this.isInput)
					this.format = this.$element.data('format');
				else
					this.format = this.$element.find('input').data('format');
				if (!this.format){
					if (this.pickDate && this.pickTime) {
						this.format = 'yyyy-MM-dd hh:mm:ss';
					} else if (this.pickDate) {
						this.format = 'yyyy-MM-dd';
					} else if (this.pickTime) {
						this.format = 'hh:mm:ss';
					}
					//如果配置了只选择年月，日期格式为年-月
					if(this.pickMonth){
						this.format = 'yyyy-MM';
					}
				}
			}
			this._compileFormat();
			if (this.component) {
				icon = this.component.find('i');
			}
			if (this.pickTime) {
				if (icon && icon.length)
					this.timeIcon = icon.data('time-icon');
				if (!this.timeIcon)
					this.timeIcon = 'icon-time';
				icon.addClass(this.timeIcon);
			}
			if (this.pickDate) {
				if (icon && icon.length)
					this.dateIcon = icon.data('date-icon');
				if (!this.dateIcon)
					this.dateIcon = 'icon-calendar';
				icon.removeClass(this.timeIcon);
				icon.addClass(this.dateIcon);
			}

		
			this.widget = $(
				getTemplate({manyDate:this.manyDate,timeIcon:this.timeIcon,pickDate:options.pickDate,pickTime:options.pickTime,is12Hours:options.pick12HourFormat,showSeconds:options.pickSeconds,collapse:options.collapse})).appendTo('body');
			this.minViewMode = options.minViewMode || this.$element.data('date-minviewmode') || 0;
			if (typeof this.minViewMode === 'string') {
				switch (this.minViewMode) {
				case 'months':
					this.minViewMode = 1;
					break;
				case 'years':
					this.minViewMode = 2;
					break;
				default:
					this.minViewMode = 0;
					break;
				}
			}
			this.viewMode = options.viewMode || this.$element.data('date-viewmode') || 0;
			if (typeof this.viewMode === 'string') {
				switch (this.viewMode) {
				case 'months':
					this.viewMode = 1;
					break;
				case 'years':
					this.viewMode = 2;
					break;
				default:
					this.viewMode = 0;
					break;
				}
			}
			
			//如果配置了只选择到月，设置当前视图，和最小视图到月份
			if(this.pickMonth){
				this.viewMode = 1;
				this.minViewMode = 1;
			}
			
			this.startViewMode = this.viewMode;
			this.weekStart = options.weekStart || this.$element.data('date-weekstart') || 0;
			this.weekEnd = this.weekStart === 0 ? 6 : this.weekStart - 1;
			this.setStartDate(options.startDate || this.$element.data('date-startdate'));
			this.setEndDate(options.endDate || this.$element.data('date-enddate'));
			this.fillDow();
			
			this.fillMonths();
			
			this.fillHours();
			this.fillMinutes();
			this.fillSeconds();
			
			this.update();
			
			this.showMode();

			this._attachDatePickerEvents();
			var self = this;
			$(this.$element).unbind('click');				    
			$(this.$element).bind('click',function(){
				//添加readonly识别
				if(!$(self.$element).attr("readonly")){
					if(self.manyDate) {
						self.startInput =  $(self.$element).attr('start');
						self.endInput = $(self.$element).attr('end');
					}
					self.show();
				}
			});
		 if(this.$element.attr('data-defaultData')){
			 this.setValue(this.$element.attr('data-defaultData'));
		 }   			
	    },
		startInput: undefined,
		endInput: undefined,

	    show: function(e) {
	      //this.widget.show();
	      this.height = this.component ? this.component.outerHeight() : this.$element.outerHeight();
	      this.place();
		  this._show();
	      this.$element.trigger({
	        type: 'show',
	        date: this._date
	      });
	      this._attachDatePickerGlobalEvents();
		 
	      if (e) {
	        e.stopPropagation();
	        e.preventDefault();
	      }
	    },
		_show: function(){
			$(this.widget).css({'display':'block'});
			//!$(this.widget).hasClass('state') && $(this.widget).addClass('state');
		},
	    disable: function(){
	          this.$element.find('input').prop('disabled',true);
	          this._detachDatePickerEvents();
	    },
	    enable: function(){
	          this.$element.find('input').prop('disabled',false);
	          this._attachDatePickerEvents();
	    },

	    hide: function() {
	      var e = arguments.length==1 ? arguments[0]:{};
	      var that = this;
	      // Ignore event if in the middle of a picker transition
	      var collapse = this.widget.find('.collapse');
	      for (var i = 0; i < collapse.length; i++) {
	        var collapseData = collapse.eq(i).data('collapse');
	        if (collapseData && collapseData.transitioning)
	          return;
	      }
	      if(arguments.length==1 && $(e.target).parent().is("td")||$(e.target).parent().parent().parent().hasClass("table-condensed")){
	    	  return;
	      }
	      this.widget.hide();
	      this.viewMode = this.startViewMode;
	      this.showMode();
	      this.set();
	      this.$element.trigger({
	        type: 'hide',
	        date: this._date
	      });
	      this._detachDatePickerGlobalEvents();
	      //如果是双面板 则判断是否清空
	      if(this.manyDate){
	    	 !(this.ret[0] && this.ret[1]) && this.$element.val('');	    	  
	      }
	      this.unbindmanydate();
	      $(".manydate-show").hide();
	    },
	    unbindmanydate:function(){
	    	$(".manydate-show-month").unbind('click.zhanghuan');
	    	$(".manydate-show-year").unbind('click.zhanghuan2');
	    },
		ret: [],
		panelCount: 0,
		panelCount: 0,
	    set: function(target,t) {
	      var formatted = '',
			  targetParent = $(target).closest('.datepicker');
		
		  // 点击元素增加类
		  $(targetParent).find('.day') && $(targetParent).find('.day').removeClass('active');
		  $(target).hasClass('day') && !$(target).hasClass('active') && $(target).addClass('active');
		  
		 if (!this._unset) {
			if(this.manyDate) {
				if($(targetParent).hasClass('panel-st')) {
					formatted = this.formatDate(this._date);

				 }else if($(targetParent).hasClass('panel-nd')){
					formatted = this.formatDate(this._date2);
				 }
			}else{
				formatted = this.formatDate(this._date);
			}
			
		 }
	      if (!this.isInput) {
	        if (this.component){
	          var input = this.$element.find('input');
	          input.val(formatted);

	          this._resetMaskPos(input);
			  // buy tugenhua new add
			  if($(target).hasClass('day')) {
				  //$(this.widget).hasClass('state') && $(this.widget).removeClass('state');
				  $(this.widget).css({'display':'none'});
			  }
	        }
	        this.$element.data('date', formatted);
	      } else {
			  if(this.manyDate) {
				  var result = true;
				  if($(target).hasClass('day')) {
					 var ret1,
					     ret2;
					 if($(targetParent).hasClass('panel-st')){
						this.ret[0] = formatted;
					  }else if($(targetParent).hasClass('panel-nd')){
							this.ret[1] = formatted;
					  }
					  if(this.ret[0] == undefined) {
							this.ret[0] = '';
							this.$element.val(this.ret[0]);
					  }

					  if(this.ret[0] &&  this.ret[1]) {
							 ret1 = Date.parse(this.ret[0]);
							 ret2 = Date.parse(this.ret[1]);
					  }
					  if(ret1 > ret2) {
						 this.hide();
						  HZBank.showWarn('结束日期必须大于开始日期');
						 $(target).hasClass('active') && $(target).removeClass('active');
						 if($(targetParent).hasClass('panel-st')){
								this.ret[0] = '';
						 }else if($(targetParent).hasClass('panel-nd')){
									this.ret[1] = '';
						 }
						 return false;
					  }else {
						if(this.ret[0] == '' || this.ret[1] == '') {
							if(this.ret[0] !== ''){
								var valFormat = this.ret[0] + this.ret[1];
							}
							
						} else {
							
							// 动态设置input隐藏域值  为了开发人员容易获取
						    if(this.ret[0]) {
							    var elemParent = $(this.$element).parent(),
								    start = $('.start-input',elemParent),
								    startName = $(start).attr('name');
							    if(startName == this.startInput) {
							    	$(start).attr('value',this.ret[0]);
							    }
						    }
							if(this.ret[1]) {
								var elemParent = $(this.$element).parent(),
							  		end = $('.end-input',elemParent),
							  		endName = $(end).attr('name');
								if(endName == this.endInput) {
									$(end).attr('value',this.ret[1]);
								}  
							}
							//undo
							if(this.ret[1] == undefined) {
								var valFormat = this.ret[0];
							}else {
								var valFormat = this.ret[0] + ' / ' + this.ret[1];
							}
							
						}
						this.$element.val(valFormat);
					  }
					  var elemVal = $(this.$element).val();
					  //zhanghuan--for bug
					  if(arguments.length==3 && arguments[2]=='m'){
						  if(/\//.test(elemVal)) {
							  //$(this.widget).hasClass('state') && $(this.widget).removeClass('state');
							  $(this.widget).css({'display':'none'});
							  var index = elemVal.indexOf('/')+2;
							  this.ret[0] = elemVal.substr(0,10);
							  this.ret[1] = elemVal.substr(index,10);
						  }
					  }
				  }
			  }else {
					// buy tugenhua new add
					if($(target).hasClass('day')) {
						//$(this.widget).hasClass('state') && $(this.widget).removeClass('state');
						$(this.widget).css({'display':'none'});
					}
					var result = this.inputcheck(this.$element.val());
					if((result||result.length==0)&&arguments.length==0){
						this.$element.val(result)
					}else{
						this.$element.val(formatted);
					}
					// 如果没有传参，即不是切换面板，是赋值
					if(arguments.length==0){
						// 刷新面板数据，解决input输入YYYYMMDD类格式时，正则判断格式不通过，不跟新面板数据
						// 已经过inputcheck验证，应该更新数据
						this.update();
						this.notifyChange();
					}

					this._resetMaskPos(this.$element);
			  }
	      }
	    },
	    //多面板input输入验证--------zhanghuan
	    manyinputcheck:function(){
	    	var data = this.$element.val();
	    	if((!data) || data.replace(/[ ]/g,'').length==0 || data.indexOf('/')<0){
	    		this.$element.val('');
	    		return;
	    	}
	    	 data = data.replace(/[ ]/g , '').split('/');
	    	 if((!data[0]) || (!data[1])){
	    		 this.$element.val('');
		    	 return;
	    	 }
	    	 var t1 = this.inputcheck(data[0]);
	    	 var t2 = this.inputcheck(data[1]);
	    	 if(t1 && t2){
//	    		 this.$element.val(t1+' / '+ t2);
	    		 this.setValue(t1+'/'+ t2);
	    	 }else{
	    		 this.$element.val('');
	    	 }
	    	
	    },
	    inputcheck:function(t){
	    	if(t.replace(/ /g,'').length==0){
	    		return '';
	    	}
	    	if(t.indexOf(':')>-1){
	    		return t;
	    	}
	    	var r = new Date(t);
	    	if(isNaN(r.getTime())){
	    		return '';
	    	}
	    	if(t.indexOf(':')>-1){
	    		return t;
	    	}
	    	////console.log(this.$element.attr('data-type'));
	    	if (this.$element.attr('data-type') == 'date-time'){
	    		var val = t.replace(/ /g,'').replace(/:/g,'').replace(/-/g,'').substring(0,14);
		    	var reg = new RegExp('\\d{14}');
		    		if(reg.test(val)){
		    			var y =parseInt(val.substring(0,4)),
		    				m = parseInt(val.substring(4,6)),
		    				d =parseInt(val.substring(6,8)),
		    				h =parseInt(val.substring(8,10)),
		    				mi =parseInt(val.substring(10,12)),
		    				s =parseInt(val.substring(12,14)),
		    				boolean_y,
		    				boolean_m,
		    				boolean_d,
		    				boolen_h,
		    				boolen_mi,
		    				boolen_s;
		    			boolean_y = y>2099||y<1900 ? false : true;
		    			boolean_m = m>12 || m<1 ? false: true;
		    			boolean_d = d>31 || d<1 ? false: true;
		    			boolen_h = d>23 || d<0 ? false: true;
		    			boolen_mi = d>60 || d<0 ? false: true;
		    			boolen_s = d>60 || d<0 ? false: true;
		    			if(boolean_y&&boolean_m&&boolean_d&&boolen_h&&boolen_mi&&boolen_s){
		    				return y+'-'+(m<10 ? '0'+m : m)+'-'+(d<10 ? '0'+d : d)+" "+h+":"+mi+":"+s;
		    			}
		    		}
	    	}else{
		    	
		    	//如果是只选择年月
		    	if(this.pickMonth){
		    		var val = t.replace(/-/g,'').substring(0,6);
		        	var reg = new RegExp('\\d{6}');
		    		if(reg.test(val)){
		    			var y =parseInt(val.substring(0,4)),
		    				m = parseInt(val.substring(4,6)),
		    				boolean_y,
		    				boolean_m;
		    			boolean_y = y>2099||y<1900 ? false : true;
		    			boolean_m = m>12 || m<1 ? false: true;
		    			if(boolean_y&&boolean_m){
		    				return y+'-'+(m<10 ? '0'+m : m);
		    			}
		    		}
		    	}else{
		    		var val = t.replace(/-/g,'').substring(0,8);
			    	var reg = new RegExp('\\d{8}');
		    		if(reg.test(val)){
		    			var y =parseInt(val.substring(0,4)),
		    				m = parseInt(val.substring(4,6)),
		    				d =parseInt(val.substring(6,8)),
		    				boolean_y,
		    				boolean_m,
		    				boolean_d;
		    			boolean_y = y>2099||y<1900 ? false : true;
		    			boolean_m = m>12 || m<1 ? false: true;
		    			boolean_d = d>31 || d<1 ? false: true;
		    			if(boolean_y&&boolean_m&&boolean_d){
		    				return y+'-'+(m<10 ? '0'+m : m)+'-'+(d<10 ? '0'+d : d);
		    			}
		    		}
		    	}
	
	    	}
	    		return false;
	    },
	  //多面板渲染day-----zhanghuan
	    manydateRenderDate:function(ar1,ar2){
	    	var day1 = ar1,
	    		day2 = ar2;
	    	var con1 = this.widget.find(".datepicker-days:first").children("table.table-condensed").find("tbody td").not(".old").not(".new");
	    	var con2 = this.widget.find(".datepicker-days:last").children("table.table-condensed").find("tbody td").not(".old").not(".new");
	    	con1.removeClass('active');
	    	con2.removeClass('active');
	    	this.addActive(con1,day1);
	    	this.addActive(con2,day2);
	    },
	    //高亮显示的day-----zhanghuan
	    addActive:function(tar,day){
	    	var that = this;
	    	$.each(tar,function(i,v){
	    		var n = parseInt(tar.eq(i).html());
	    		if(n==day){
	    			tar.eq(i).addClass('active');
//	    			tar.eq(i).trigger('click');
	    			that.set(tar.eq(i), true);
	    			return;
	    		}
	    	})
	    },
	    checkvalue:function(d){
	    	var data = d,
	    		f=true,
	    		s=true,
	    		all=true;
	    	if(!data[0]){
	    		f = false;
	    	}
	    	if(!data[1]){
	    		s = false;
	    	}
	    	if(f){
	    		var date =data[0].split('-');
	    		var year = this.viewDate.getUTCFullYear(),
    		    	month = this.viewDate.getUTCMonth(),
    		    	day = this.viewDate.getUTCDate();
//	    		console.log(date[0]+'****'+year);
//	    		console.log(date[1]+'****'+(month+1));
//	    		console.log(date[2]+'****'+day);
//	    		console.log(date[0]==year && date[1]==month+1 && date[2]==day)
	    		if(date[0]==year && date[1]==month+1 && date[2]==day){
	    			f=false;
	    		}
	    	}
	    	if(s){
	    		var date =data[1].split('-');
	    		var year = this.viewDate2.getUTCFullYear(),
    		    	month = this.viewDate2.getUTCMonth(),
    		    	day = this.viewDate2.getUTCDate();
//	    		console.log(date[0]+'****'+year);
//	    		console.log(date[1]+'****'+(month+1));
//	    		console.log(date[2]+'****'+day);
//	    		console.log(date[0]==year && date[1]==month+1 && date[2]==day)
	    		if(date[0]==year && date[1]==month+1 && date[2]==day){
	    			s=false;
	    		}
	    	}
	    	all = f&&s;
	    	if(all){
	    		return 3
	    	}
	    	if(f){
	    		return 1
	    	}
	    	if(s){
	    		return 2
	    	}
	    	return 0;
	    	
	    },
	    //input赋值------zhanghuan
	    setValue: function(newDate,num) {
	    	if(newDate&&typeof newDate=='string'&&newDate.indexOf('/')>-1){
	    		if (!newDate) {
	    			this._unset = true;
	    		} else {
	    			this._unset = false;
	    		}
	    		var data = newDate.replace(/[ ]/g , '').split('/');
	    		var result = this.checkvalue(data);
	    		this._date = data[0] ? this.parseDate(data[0]) : this._date;
	    		this._date2 = data[1] ? this.parseDate(data[1]) : this._date2;
//	    		this.set();
	    		try {
	    			this.viewDate = UTCDate(this._date.getUTCFullYear(), this._date.getUTCMonth(), this._date.getUTCDate(), 0, 0, 0, 0);
	    			this.viewDate2 = UTCDate(this._date2.getUTCFullYear(), this._date2.getUTCMonth(),this._date2.getUTCDate(), 0, 0, 0, 0);
				} catch (e) {
					return;
				} 
	    		var year = this.viewDate.getUTCFullYear(),
	    		    month = this.viewDate.getUTCMonth(),
					year2 = this.viewDate2.getUTCFullYear(),
					month2 = this.viewDate2.getUTCMonth(),
	    			day = this.viewDate.getUTCDate(),
	    			day2 = this.viewDate2.getUTCDate();
	    		 this.count = 0;
	    		 this.count2 = 0;
	    		 this.dateTemp = month;
				 this.tempYear = year;
				 this.dateTemp2 = month2;
				 this.tempYear2 = year2;
	    		this.fillDate();
	    		this.fillTime();
	    		//多面板渲染day-----zhanghuan
	    		var n = arguments.length==2 ? arguments[1] : result;
	    		this.manydatehtml({year:year,month:month,day:day,year2:year2,month2:month2,day2:day2,num:n});
	    		this.manydateRenderDate(day,day2);
	    	}else{
	    		if (!newDate) {
	    			this._unset = true;
	    		} else {
	    			this._unset = false;
	    		}
	    		if (typeof newDate === 'string') {
	    			this._date = this.parseDate(newDate);
	    		} else if(newDate) {
	    			this._date = new Date(newDate);
	    		}
	    		
	    		this.set();
	    		this.viewDate = UTCDate(this._date.getUTCFullYear(), this._date.getUTCMonth(), 1, 0, 0, 0, 0);
	    		this.viewDate2 = UTCDate(this._date2.getUTCFullYear(), this._date2.getUTCMonth(), 1, 0, 0, 0, 0);
	    		this.fillDate();
	    		this.fillTime();
	    	}
	    },

	    getDate: function() {
	      if (this._unset) return null;
	      return new Date(this._date.valueOf());
	    },

	    setDate: function(date) {
	      if (!date) this.setValue(null);
	      else this.setValue(date.valueOf());
	    },

	    setStartDate: function(date) {
	      if (date instanceof Date) {
	        this.startDate = date;
	      } else if (typeof date === 'string') {
	        this.startDate = new UTCDate(date);
	        if (! this.startDate.getUTCFullYear()) {
	          this.startDate = -Infinity;
	        }
	      } else {
	        this.startDate = -Infinity;
	      }
	      if (this.viewDate) {
	        this.update();
	      }
	    },

	    setEndDate: function(date) {
	      if (date instanceof Date) {
	        this.endDate = date;
	      } else if (typeof date === 'string') {
	        this.endDate = new UTCDate(date);
	        if (! this.endDate.getUTCFullYear()) {
	          this.endDate = Infinity;
	        }
	      } else {
	        this.endDate = Infinity;
	      }
	      if (this.viewDate) {
	        this.update();
	      }
	    },

	    getLocalDate: function() {
	      if (this._unset) return null;
	      var d = this._date;
	      return new Date(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(),
	                      d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds());
	    },

	    setLocalDate: function(localDate) {
	      if (!localDate) this.setValue(null);
	      else
	        this.setValue(Date.UTC(
	          localDate.getFullYear(),
	          localDate.getMonth(),
	          localDate.getDate(),
	          localDate.getHours(),
	          localDate.getMinutes(),
	          localDate.getSeconds(),
	          localDate.getMilliseconds()));
	    },

	    place: function(){
	      var position = 'absolute';
	      var offset = this.component ? this.component.offset() : this.$element.offset();
	      this.width = this.component ? this.component.outerWidth() : this.$element.outerWidth();
	      offset.top = offset.top + this.height;

	      var $window = $(window);
	      
	      if ( this.options.width != undefined ) {
	        this.widget.width( this.options.width );
	      }
	      
	      if ( this.options.orientation == 'left' ) {
	        this.widget.addClass( 'left-oriented' );
	        offset.left   = offset.left - this.widget.width() + 20;
	      }
	      
	      if (this._isInFixed()) {
	        position = 'fixed';
	        offset.top -= $window.scrollTop();
	        offset.left -= $window.scrollLeft();
	      }

	      if ($window.width() < offset.left + this.widget.outerWidth()) {
	        offset.right = $window.width() - offset.left - this.width;
	        offset.left = 'auto';
	        this.widget.addClass('pull-right');
	      } else {
	        offset.right = 'auto';
	        this.widget.removeClass('pull-right');
	      }
	      var _left = this.$element.offset().left-43;
	      var _width = this.widget.find('.ui-hz-widget').eq(0).width()*2;
	      var _win = $('body').width();
	      if(_left+_width>_win){
	    	  _left = _win - _width -50;
	      }
	      //多面板自适应判断，被遮挡则向上弹出---zhanghuan
	      if(this.manyDate) {
	    	  var wtop = $(window).height(),
	    	  	  newtop2;
	    	  if(offset.top+this.widget.height()+10 > wtop){
	    		  newtop2 = offset.top - this.widget.height() -  this.$element.height(); 
	    	  }else{
	    		  newtop2 = offset.top;
	    	  }
	    //可配置弹出的方向
	    	  if(this.$element.data('direct')=='top'){
	    		  newtop2 = offset.top - this.widget.height() -  this.$element.height();
	    	  }else if(this.$element.data('direct')=='bottom'){
	    		  newtop2 = offset.top;
	    	  }
	    	  this.widget.css({
	  	        position: position,
	  	        top: newtop2,
	  	        left: _left,
	  	        zIndex:3000
	  	      });
	    	//单面板自适应判断，被遮挡则向上弹出---zhanghuan
	      }else {
	    	  var _offset = this.newplace(offset);
	    	  var wtop = $(window).height(),
	    	  	  newtop;
	    	  if(_offset.top+this.widget.height()+10 > wtop){
	    		  newtop =  _offset.top - this.widget.height() -  this.$element.height(); 
	    	  }else{
	    		  newtop =  _offset.top;
	    	  }
	    	  if(this.$element.data('direct')=='top'){
	    		  newtop = _offset.top - this.widget.height() -  this.$element.height();
	    	  }else if(this.$element.data('direct')=='bottom'){
	    		  newtop = _offset.top;
	    	  }
	    	  this.widget.css({
	  	        position: position,
	  	        top: newtop,
	  	        left: _offset.left,
	  	        right: _offset.right
	  	      });
	      }
	      
	    },
	    newplace:function(of){
	    	var offset = of;
	    	var h = this.widget.height();
	    	if(this.position=='top'){			//offset.top+h>$('body').height()-10 || 
	    		offset.top = offset.top - this.height - h;
	    	}
	    	return offset;
	    },
	    changeFunc: function(fun) {
	    	if(typeof fun === 'function'){
	    		this.changeFun = fun;
	    	}
	    },
	    notifyChange: function(){
	      this.$element.trigger({
	        type: 'changeDate',
	        date: this.getDate(),
	        localDate: this.getLocalDate()
	      });
	      if(this.changeFun&&typeof this.changeFun==='function'){
	    	  this.changeFun.call(this.$element);
	      }
	    },

	    update: function(newDate){
			
	      var dateStr = newDate;
		  
	      if (!dateStr) {
	        if (this.isInput) {
	          dateStr = this.$element.val();
	        } else {
	          dateStr = this.$element.find('input').val();
	        }
	        if (dateStr) {
	          this._date = this.parseDate(dateStr);
			  
			  this._date2 = this.parseDate(dateStr);
			  
	        }
	        if (!this._date) {
	          var tmp = new Date();
	          this._date = UTCDate(tmp.getFullYear(),
	                              tmp.getMonth(),
	                              tmp.getDate(),
	                              tmp.getHours(),
	                              tmp.getMinutes(),
	                              tmp.getSeconds(),
	                              tmp.getMilliseconds());
	        }
			if(!this._date2) {
				var tmp = new Date();
				this._date2 = UTCDate(tmp.getFullYear(),
	                              tmp.getMonth(),
	                              tmp.getDate(),
	                              tmp.getHours(),
	                              tmp.getMinutes(),
	                              tmp.getSeconds(),
	                              tmp.getMilliseconds());
			}
			  
	      }
	      this.viewDate = UTCDate(this._date.getUTCFullYear(), this._date.getUTCMonth(), 1, 0, 0, 0, 0);
		  this.viewDate2 = UTCDate(this._date2.getUTCFullYear(), this._date2.getUTCMonth(), 1, 0, 0, 0, 0);
	      this.fillDate();
	      this.fillTime();
	    },

	    fillDow: function() {
	      var dowCnt = this.weekStart;
	      var html = $('<tr>');
	      while (dowCnt < this.weekStart + 7) {
	        html.append('<th class="dow">' + dates[this.language].daysMin[(dowCnt++) % 7] + '</th>');
	      }
	      this.widget.find('.datepicker-days thead').append(html);
	    },

	    fillMonths: function() {
	      var html = '';
	      var i = 0
	      while (i < 12) {
	        html += '<span class="month">' + dates[this.language].monthsShort[i++] + '</span>';
	      }
	      this.widget.find('.datepicker-months td').append(html);
	    },
		dateFlag: true,
		dateFlag2: true,
		dateFlag3: true,
		dateTemp: 0,
		dateTemp2: 0,
		count: 0,
		count2: 0,
		tempYear: 0,
		tempYear2: 0,
	    fillDate: function(target) {
	      var self = this,
			  year = this.viewDate.getUTCFullYear(),
			  month = this.viewDate.getUTCMonth(),
			  year2 = this.viewDate2.getUTCFullYear(),
			  month2 = this.viewDate2.getUTCMonth();
	      var currentDate = UTCDate(
	        this._date.getUTCFullYear(),
	        this._date.getUTCMonth(),
	        this._date.getUTCDate(),
	        0, 0, 0, 0
	      );
	      var startYear  = typeof this.startDate === 'object' ? this.startDate.getUTCFullYear() : -Infinity;
	      var startMonth = typeof this.startDate === 'object' ? this.startDate.getUTCMonth() : -1;
	      var endYear  = typeof this.endDate === 'object' ? this.endDate.getUTCFullYear() : Infinity;
	      var endMonth = typeof this.endDate === 'object' ? this.endDate.getUTCMonth() : 12;
	
	      this.widget.find('.datepicker-days').find('.disabled').removeClass('disabled');
	      this.widget.find('.datepicker-months').find('.disabled').removeClass('disabled');
	      this.widget.find('.datepicker-years').find('.disabled').removeClass('disabled');
		  if(this.dateFlag2) {
			  this._dataHTML({year:year,currentDate:currentDate,month:month,endMonth:endMonth,startMonth:startMonth,startYear:startYear,endYear:endYear,target:target});
			  this.dateFlag2 = false;
		  }
		  if(this.manyDate) {
			 !$(target).closest('.datepicker-days').hasClass('current') && 
			 $(target).closest('.datepicker-days').addClass('current');
			 
			 !$(target).closest('.datepicker-days').hasClass('show-month') && 
			 $(target).closest('.datepicker-days').addClass('show-month');
			 var html = dates[this.language].months[month] + ' ' + year;
			 var html2 = dates[this.language].months[month2] + ' ' + year2;
			 var con =  this.widget.find('.datepicker-days:first th:eq(1)');
			 var con2 =  this.widget.find('.datepicker-days:last th:eq(1)');
			  // 页面一开始渲染出来 
			  if(this.dateFlag) {
//				 $('.many-date').each(function(i,item) {
					con.text(html);
				    con.attr({'month':dates[self.language].months[month]});
				    con.attr({'year':year});
				    con.addClass('newAdd');
				   
				   con2.text(html);
				   con2.attr({'month':dates[self.language].months[month]});
				   con2.attr({'year':year});
				   con2.addClass('newAdd');
//				 });
				 

				 this.dateFlag = false;
				 this.dateTemp = month;
				 this.tempYear = year;

				 this.dateTemp2 = month2;
				 this.tempYear2 = year2;
			  }else{
				  //多面板增加重新赋值的功能---zhanghuan
				  con.html(html);
				  con2.html(html2);
//						$('.datepicker-days:first th:eq(1)',item).text(html);
//					    $('.datepicker-days:first th:eq(1)',item).attr({'month':dates[self.language].months[month]});
//					    $('.datepicker-days:first th:eq(1)',item).attr({'year':year});
//					    $(' .datepicker-days:first th:eq(1)',item).addClass('newAdd');
//					   $('.datepicker-days:last th:eq(1)',item).text(html2);
//					   $('.datepicker-days:last th:eq(1)',item).attr({'month':dates[self.language].months[month2]});
//					   $('.datepicker-days:last th:eq(1)',item).attr({'year':year2});
//					   $('.datepicker-days:last th:eq(1)',item).addClass('newAdd');
//					 this.dateFlag = false;
//					 this.dateTemp = month;
//					 this.tempYear = year;
//
//					 this.dateTemp2 = month2;
//					 this.tempYear2 = year2;
			//end  
			  }
			 
			 // 当点击prev next按钮时候 再去判断是那个面板 再去渲染下月份和年份
			 $('.many-date').each(function(j,item) {
				if($('.datepicker-days:first',item).hasClass('current')) {
				  var dateparent = $('.datepicker-days:first',item).find('th:eq(1)');
				 if($(target).hasClass('prev')) {
					 self.count--
					 if(self.dateTemp + self.count < 0) {

						 //由于月份是从0开始的 所以还要减去1
						 self.count = 12 - self.dateTemp - 1;
						 self.tempYear--;
					 }
					 var html = dates[self.language].months[self.dateTemp + self.count] + ' ' + self.tempYear;
					 $(dateparent).html(html);
					 $(dateparent).attr({'month':self.dateTemp + self.count,'year':self.tempYear});
					 $(target).closest('.datepicker-days').removeClass('current');
					 var tempMonth = self.dateTemp + self.count;
					 self._dataHTML({year:self.tempYear,currentDate:currentDate,month:tempMonth,startMonth:startMonth,endMonth:endMonth,startYear:startYear,endYear:endYear,target:target});
				 }else {
					self.count++;
					if(self.dateTemp + self.count >= 12) {
						self.count = 0;
						self.dateTemp = 0;
						self.tempYear++;
					 }
					 var html = dates[self.language].months[self.dateTemp + self.count] + ' ' + self.tempYear;
					 $(dateparent).html(html);
					 $(dateparent).attr({'month':self.dateTemp + self.count,'year':self.tempYear});
					 $(target).closest('.datepicker-days').removeClass('current');
					 var tempMonth = self.dateTemp + self.count;
					 self._dataHTML({year:self.tempYear,month:tempMonth,currentDate:currentDate,startMonth:startMonth,endMonth:endMonth,startYear:startYear,endYear:endYear,target:target});
				 } 
			 } else if($('.datepicker-days:last',item).hasClass('current')){
				 var dateparent = $('.datepicker-days:last',item).find('th:eq(1)');
				 if($(target).hasClass('prev2')) {
					self.count2--;
					if(self.dateTemp2 + self.count2 < 0) {
						//由于月份是从0开始的 所以还要减去1
						 self.count2 = 12 - self.dateTemp2 - 1;
						 self.tempYear2--;
					}
					var html = dates[self.language].months[self.dateTemp2 + self.count2] + ' ' + self.tempYear2;
					$(dateparent).html(html);
					$(dateparent).attr({'month':self.dateTemp2 + self.count2,'year':self.tempYear2});
					$(target).closest('.datepicker-days').removeClass('current');
					var tempMonth = self.dateTemp2 + self.count2;
					self._dataHTML({year:self.tempYear2,month:tempMonth,currentDate:currentDate,startMonth:startMonth,endMonth:endMonth,startYear:startYear,endYear:endYear,target:target});
				 }else {
					self.count2++;
					if(self.dateTemp2 + self.count2 >= 12) {
						self.count2 = 0;
						self.dateTemp2 = 0;
						self.tempYear2++;
					}
					var html = dates[self.language].months[self.dateTemp2 + self.count2] + ' ' + self.tempYear2;
					$(dateparent).html(html);
					$(dateparent).attr({'month':self.dateTemp2 + self.count2,'year':self.tempYear2});
					$(target).closest('.datepicker-days').removeClass('current');
					var tempMonth = self.dateTemp2 + self.count2;
					self._dataHTML({year:self.tempYear2,month:tempMonth,currentDate:currentDate,startMonth:startMonth,endMonth:endMonth,startYear:startYear,endYear:endYear,target:target});
				 }
			 }
			 });
		  }else {
			this.widget.find('.datepicker-days th:eq(1)').text(
	          dates[this.language].months[month] + ' ' + year); 
			this._dataHTML({year:year,month:month,startMonth:startMonth,endMonth:endMonth,currentDate:currentDate,startYear:startYear,endYear:endYear,target:target});
		  }
	    },
	    //多面板渲染日期day，修复bug。-------zhanghuan
	    manydatehtml:function(cfg){
	    	var year = cfg.year,
	    		month = cfg.month,
	    		currentDate = cfg.day, 
	    	    year2 = cfg.year2,
	    		month2 = cfg.month2,
	    		currentDate2 = cfg.day2,
	    		target = this.widget.find('.prev')[0],
	    		target2 = this.widget.find('.prev2')[0],
	    		num = cfg.num;
	    	var startYear  = typeof this.startDate === 'object' ? this.startDate.getUTCFullYear() : -Infinity;
	  	    var startMonth = typeof this.startDate === 'object' ? this.startDate.getUTCMonth() : -1;
	  	    var endYear  = typeof this.endDate === 'object' ? this.endDate.getUTCFullYear() : Infinity;
	  	    var endMonth = typeof this.endDate === 'object' ? this.endDate.getUTCMonth() : 12;
	  	    if(num==1){
	  	    	this._dataHTML({year:year,month:month,currentDate:currentDate,startMonth:startMonth,endMonth:endMonth,startYear:startYear,endYear:endYear,target:target},'f');
	  	    }else if(num==2){
	  	    	this._dataHTML({year:year2,month:month2,currentDate:currentDate2,startMonth:startMonth,endMonth:endMonth,startYear:startYear,endYear:endYear,target:target2},'s');
	  	    }else if(num==3){
	  	    	this._dataHTML({year:year,month:month,currentDate:currentDate,startMonth:startMonth,endMonth:endMonth,startYear:startYear,endYear:endYear,target:target},'f');
	  	    	this._dataHTML({year:year2,month:month2,currentDate:currentDate2,startMonth:startMonth,endMonth:endMonth,startYear:startYear,endYear:endYear,target:target2},'s');
	  	    }
	    },
		_dataHTML:function(cfg,none){
			var self = this,
				year = cfg.year,
				month = cfg.month,
				startMonth = cfg.startMonth,
				endMonth = cfg.endMonth,
				startYear = cfg.startYear,
				endYear = cfg.endYear,
				currentDate = cfg.currentDate,
				target = cfg.target;
			var prevMonth = UTCDate(year, month-1, 28, 0, 0, 0, 0);
	        var day = DPGlobal.getDaysInMonth(
	        prevMonth.getUTCFullYear(), prevMonth.getUTCMonth());
	        prevMonth.setUTCDate(day);
	        prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.weekStart + 7) % 7);
	        if ((year == startYear && month <= startMonth) || year < startYear) {
	            this.widget.find('.datepicker-days th:eq(0)').addClass('disabled');
	       }
	      if ((year == endYear && month >= endMonth) || year > endYear) {
	        this.widget.find('.datepicker-days th:eq(2)').addClass('disabled');
	      }
	      var nextMonth = new Date(prevMonth.valueOf());                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              
	      nextMonth.setUTCDate(nextMonth.getUTCDate() + 42);
	      nextMonth = nextMonth.valueOf();
	      var html = [];
	      var row;
	      var clsName;
	      while (prevMonth.valueOf() < nextMonth) {
	        if (prevMonth.getUTCDay() === this.weekStart) {
	          row = $('<tr>');
	          html.push(row);
	        }
	        clsName = '';
	        if (prevMonth.getUTCFullYear() < year ||
	            (prevMonth.getUTCFullYear() == year &&
	             prevMonth.getUTCMonth() < month)) {
			  if(this.manyDate) {
				 clsName += ' old disabled';
			  }else {
				 clsName += ' old';
			  }
	          
	        } else if (prevMonth.getUTCFullYear() > year ||
	                   (prevMonth.getUTCFullYear() == year &&
	                    prevMonth.getUTCMonth() > month)) {
			  if(this.manyDate) {
				 clsName += ' new disabled';
			  }else {
				 clsName += ' new';
			  }
	          
	        }
	        if (prevMonth.valueOf() === currentDate.valueOf()) {
	            clsName += ' active';
	        }
	        if ((prevMonth.valueOf() + 86400000) <= this.startDate) {
	          clsName += ' disabled';
	        }
	        if (prevMonth.valueOf() > this.endDate) {
	          clsName += ' disabled';
	        }
	        row.append('<td class="day' + clsName + '">' + prevMonth.getUTCDate() + '</td>');

	        prevMonth.setUTCDate(prevMonth.getUTCDate() + 1);
	      }
		  if(this.manyDate) {
			  if(this.dateFlag3) {
				  this.dateFlag3 = false;
				  // 默认情况下渲染day出来
				  this.widget.find('.datepicker-days tbody').empty().append(html);
			 }
			  if(arguments.length==1){
				  $('.many-date').each(function(i,item){
					  if($('.datepicker-days:first',item).hasClass('show-month')) {
						  $('.datepicker-days:first',item).find('tbody').empty().append(html);
						  $(target).closest('.datepicker-days').removeClass('show-month');
					  }else if($('.datepicker-days:last',item).hasClass('show-month')){
						  $('.datepicker-days:last',item).find('tbody').empty().append(html);
						  $(target).closest('.datepicker-days').removeClass('show-month');
					  }
					  $(this).children().each(function(i,item){
						  $('.datepicker-days:last .day',item).hasClass('active') &&
						  $('.datepicker-days:last .day',item).removeClass('active');
					  });	
				  });
			  }else{
				  if(arguments[1]=='f'){
//					  $('.many-date').each(function(i,item){
//						  $('.datepicker-days:first',item).find('tbody').empty().append(html);
						  $(target).closest('.datepicker-days').removeClass('show-month');
//						  $(this).children().each(function(i,item){
//							  $('.datepicker-days:last .day',item).hasClass('active') &&
//							  $('.datepicker-days:last .day',item).removeClass('active');
//						  });	
//					  });
					  self.widget.find('.panel-st').find('tbody').empty().append(html);
				  }else{
//					  $('.many-date').each(function(i,item){
//						  $('.datepicker-days:last',item).find('tbody').empty().append(html);
						  $(target).closest('.datepicker-days').removeClass('show-month');
//						  $(this).children().each(function(i,item){
//							  $('.datepicker-days:last .day',item).hasClass('active') &&
//							  $('.datepicker-days:last .day',item).removeClass('active');
//						  });	
//					  });
					  self.widget.find('.panel-nd').find('tbody').empty().append(html);
				  }
			  }
		  }else {
			 this.widget.find('.datepicker-days tbody').empty().append(html);
		  }
	      var currentYear = this._date.getUTCFullYear();
	
	      var months = this.widget.find('.datepicker-months').find(
	        'th:eq(1)').text(year).end().find('span').removeClass('active');
	      if (currentYear === year) {
	        months.eq(this._date.getUTCMonth()).addClass('active');
	      }
	      if (currentYear - 1 < startYear) {
	        this.widget.find('.datepicker-months th:eq(0)').addClass('disabled');
	      }
	      if (currentYear + 1 > endYear) {
	        this.widget.find('.datepicker-months th:eq(2)').addClass('disabled');
	      }
	      for (var i = 0; i < 12; i++) {
	        if ((year == startYear && startMonth > i) || (year < startYear)) {
	          $(months[i]).addClass('disabled');
	        } else if ((year == endYear && endMonth < i) || (year > endYear)) {
	          $(months[i]).addClass('disabled');
	        }
	      }
	      html = '';
	      year = parseInt(year/10, 10) * 10;
	      var yearCont = this.widget.find('.datepicker-years').find(
	        'th:eq(1)').text(year + '-' + (year + 9)).end().find('td');
	      this.widget.find('.datepicker-years').find('th').removeClass('disabled');
	      if (startYear > year) {
	        this.widget.find('.datepicker-years').find('th:eq(0)').addClass('disabled');
	      }
	      if (endYear < year+9) {
	        this.widget.find('.datepicker-years').find('th:eq(2)').addClass('disabled');
	      }
	      year -= 1;
	      for (var i = -1; i < 11; i++) {
	        html += '<span class="year' + (i === -1 || i === 10 ? ' old' : '') + (currentYear === year ? ' active' : '') + ((year < startYear || year > endYear) ? ' disabled' : '') + '">' + year + '</span>';
	        year += 1;
	      }
	      yearCont.html(html);
		},
	    fillHours: function() {
	      var table = this.widget.find(
	        '.timepicker .timepicker-hours table');
	      table.parent().hide();
	      var html = '';
	      if (this.options.pick12HourFormat) {
	        var current = 1;
	        for (var i = 0; i < 3; i += 1) {
	          html += '<tr>';
	          for (var j = 0; j < 4; j += 1) {
	             var c = current.toString();
	             html += '<td class="hour">' + padLeft(c, 2, '0') + '</td>';
	             current++;
	          }
	          html += '</tr>'
	        }
	      } else {
	        var current = 0;
	        for (var i = 0; i < 6; i += 1) {
	          html += '<tr>';
	          for (var j = 0; j < 4; j += 1) {
	             var c = current.toString();
	             html += '<td class="hour">' + padLeft(c, 2, '0') + '</td>';
	             current++;
	          }
	          html += '</tr>'
	        }
	      }
	      table.html(html);
	    },

	    fillMinutes: function() {
	      var table = this.widget.find(
	        '.timepicker .timepicker-minutes table');
	      table.parent().hide();
	      var html = '';
	      var current = 0;
	      for (var i = 0; i < 5; i++) {
	        html += '<tr>';
	        for (var j = 0; j < 4; j += 1) {
	          var c = current.toString();
	          html += '<td class="minute">' + padLeft(c, 2, '0') + '</td>';
	          current += 3;
	        }
	        html += '</tr>';
	      }
	      table.html(html);
	    },

	    fillSeconds: function() {
	      var table = this.widget.find(
	        '.timepicker .timepicker-seconds table');
	      table.parent().hide();
	      var html = '';
	      var current = 0;
	      for (var i = 0; i < 5; i++) {
	        html += '<tr>';
	        for (var j = 0; j < 4; j += 1) {
	          var c = current.toString();
	          html += '<td class="second">' + padLeft(c, 2, '0') + '</td>';
	          current += 3;
	        }
	        html += '</tr>';
	      }
	      table.html(html);
	    },

	    fillTime: function() {
	      if (!this._date)
	        return;
	      var timeComponents = this.widget.find('.timepicker span[data-time-component]');
	      var table = timeComponents.closest('table');
	      var is12HourFormat = this.options.pick12HourFormat;
	      var hour = this._date.getUTCHours();
	      var period = 'AM';
	      if (is12HourFormat) {
	        if (hour >= 12) period = 'PM';
	        if (hour === 0) hour = 12;
	        else if (hour != 12) hour = hour % 12;
	        this.widget.find(
	          '.timepicker [data-action=togglePeriod]').text(period);
	      }
	      hour = padLeft(hour.toString(), 2, '0');
	      var minute = padLeft(this._date.getUTCMinutes().toString(), 2, '0');
	      var second = padLeft(this._date.getUTCSeconds().toString(), 2, '0');
	      timeComponents.filter('[data-time-component=hours]').text(hour);
	      timeComponents.filter('[data-time-component=minutes]').text(minute);
	      timeComponents.filter('[data-time-component=seconds]').text(second);
	    },
	    juddmode:function(e){
	    	var that = $(e.target);
	    	var cutt = e.pageX,
	    		el = that.offset().left,
	    		width = that.width();
	    	var result = (e.pageX - el) > (width/2) ? 2 : 1;
	    	return result;
	    },
	    click: function(e) {
	      e.stopPropagation();
	      e.preventDefault();
	      this._unset = false;
	      var target = $(e.target).closest('span, td, th');
	      if (target.length === 1) {
	        if (! target.is('.disabled')) {
	          switch(target[0].nodeName.toLowerCase()) {
	            case 'th':
	              switch(target[0].className) {
	                case 'switch':
	                  var mode = this.juddmode(e);
	                  this.showMode(mode);
	                  break;
	                case 'switch newAdd':
	                	 var mode = this.juddmode(e);
	                	 var n = $(e.target).closest('.datepicker ').hasClass('panel-st')
		                 this.manyshowMode(mode,n);
	                	break;
	                case 'prev':
	                case 'next':
	                  var vd = this.viewDate;
	                  var navFnc = DPGlobal.modes[this.viewMode].navFnc;
	                  var step = DPGlobal.modes[this.viewMode].navStep;
	                  if (target[0].className === 'prev') step = step * -1;
	                  vd['set' + navFnc](vd['get' + navFnc]() + step);
	                  this.fillDate(target);
	                  this.set(target);
	                  break;
				   case 'prev2':
	               case 'next2':
	                  var vd = this.viewDate2;
	                  var navFnc = DPGlobal.modes[this.viewMode].navFnc;
	                  var step = DPGlobal.modes[this.viewMode].navStep;
	                  if (target[0].className === 'prev2') step = step * -1;
	                  vd['set' + navFnc](vd['get' + navFnc]() + step);
	                  this.fillDate(target);
	                  this.set(target);
	                  break;
	              }
	              break;
	            case 'span':
	              if (target.is('.month')) {
	                var month = target.parent().find('span').index(target);
	                this.viewDate.setUTCMonth(month);
	              } else {
	                var year = parseInt(target.text(), 10) || 0;
	                this.viewDate.setUTCFullYear(year);
	              }
	              if (this.viewMode !== 0) {
	                this._date = UTCDate(
	                  this.viewDate.getUTCFullYear(),
	                  this.viewDate.getUTCMonth(),
	                  this.viewDate.getUTCDate(),
	                  this._date.getUTCHours(),
	                  this._date.getUTCMinutes(),
	                  this._date.getUTCSeconds(),
	                  this._date.getUTCMilliseconds()
	                );
	                this.notifyChange();
	              }
	              this.showMode(-2);
	              this.fillDate();
	              this.set(target);
	              // 如果是只选择年月模式，且当前选择月份，选择后关闭日期选择框
	              if(this.pickMonth && target.is('.month')){
	            	  this.notifyChange();
	            	  this.hide();
	              }
	              break;
	            case 'td':
	              if (target.is('.day')) {
	                var day = parseInt(target.text(), 10) || 1;
	                var month = this.viewDate.getUTCMonth(),
						year = this.viewDate.getUTCFullYear(),
						month2 = this.viewDate2.getUTCMonth(),
						year2 = this.viewDate2.getUTCFullYear();
					if(this.manyDate){
						if (target.is('.old')) {
						    return;
							/*if(month === 0) {
								month = 11;
								year -= 1;
							}else {
								month -= 1;
							}*/
						}else if (target.is('.new')) {
	                        /*if (month == 11) {
	                            month = 0;
	                            year += 1;
	                        }else {
	                            month += 1;
	                        }*/
							return;
	                    }
					    if (target.is('.old')) {
	                        /*if (month2 === 0) {
	                            month2 = 11;
	                            year2 -= 1;
	                        } else {
	                            month2 -= 1;
	                        }*/
							return;
	                   }else if (target.is('.new')) {
	                      /* if (month2 == 11) {
	                           month2 = 0;
	                           year2 += 1;
	                       } else {
	                           month2 += 1;
	                       }*/
						   return;
	                  }
					}else {
						if (target.is('.old')) {
							if(month === 0) {
								month = 11;
								year -= 1;
							}else {
								month -= 1;
							}
						 }else if (target.is('.new')) {
							 if (month == 11) {
								 month = 0;
								 year += 1;
							 }else {
								 month += 1;
							 }
						 }
					}
	                

	                this._date = UTCDate(
	                  year, month, day,
	                  this._date.getUTCHours(),
	                  this._date.getUTCMinutes(),
	                  this._date.getUTCSeconds(),
	                  this._date.getUTCMilliseconds()
	                );
					this._date2 = UTCDate(
	                  year2, month2, day,
	                  this._date.getUTCHours(),
	                  this._date.getUTCMinutes(),
	                  this._date.getUTCSeconds(),
	                  this._date.getUTCMilliseconds()
	                );
	                this.viewDate = UTCDate(
	                  year, month, Math.min(28, day) , 0, 0, 0, 0);
	                this.fillDate();
	                if(this.manyDate){
	                	this.set(target,true,'m');
	                }else{
	                	this.set(target,true);
	                }
	                this.notifyChange();
	              }
	              break;
	          }
	        }
	      }
	    },

	    actions: {
	      incrementHours: function(e) {
	        this._date.setUTCHours(this._date.getUTCHours() + 1);
	      },

	      incrementMinutes: function(e) {
	        this._date.setUTCMinutes(this._date.getUTCMinutes() + 1);
	      },

	      incrementSeconds: function(e) {
	        this._date.setUTCSeconds(this._date.getUTCSeconds() + 1);
	      },

	      decrementHours: function(e) {
	        this._date.setUTCHours(this._date.getUTCHours() - 1);
	      },

	      decrementMinutes: function(e) {
	        this._date.setUTCMinutes(this._date.getUTCMinutes() - 1);
	      },

	      decrementSeconds: function(e) {
	        this._date.setUTCSeconds(this._date.getUTCSeconds() - 1);
	      },

	      togglePeriod: function(e) {
	        var hour = this._date.getUTCHours();
	        if (hour >= 12) hour -= 12;
	        else hour += 12;
	        this._date.setUTCHours(hour);
	      },

	      showPicker: function() {
	        this.widget.find('.timepicker > div:not(.timepicker-picker)').hide();
	        this.widget.find('.timepicker .timepicker-picker').show();
	      },

	      showHours: function() {
	        this.widget.find('.timepicker .timepicker-picker').hide();
	        this.widget.find('.timepicker .timepicker-hours').show();
	      },

	      showMinutes: function() {
	        this.widget.find('.timepicker .timepicker-picker').hide();
	        this.widget.find('.timepicker .timepicker-minutes').show();
	      },

	      showSeconds: function() {
	        this.widget.find('.timepicker .timepicker-picker').hide();
	        this.widget.find('.timepicker .timepicker-seconds').show();
	      },

	      selectHour: function(e) {
	        var tgt = $(e.target);
	        var value = parseInt(tgt.text(), 10);
	        if (this.options.pick12HourFormat) {
	          var current = this._date.getUTCHours();
	          if (current >= 12) {
	            if (value != 12) value = (value + 12) % 24;
	          } else {
	            if (value === 12) value = 0;
	            else value = value % 12;
	          }
	        }
	        this._date.setUTCHours(value);
	        this.actions.showPicker.call(this);
	      },

	      selectMinute: function(e) {
	        var tgt = $(e.target);
	        var value = parseInt(tgt.text(), 10);
	        this._date.setUTCMinutes(value);
	        this.actions.showPicker.call(this);
	      },

	      selectSecond: function(e) {
	        var tgt = $(e.target);
	        var value = parseInt(tgt.text(), 10);
	        this._date.setUTCSeconds(value);
	        this.actions.showPicker.call(this);
	      }
	    },

	    doAction: function(e) {
	      e.stopPropagation();
	      e.preventDefault();
	      if (!this._date) this._date = UTCDate(1970, 0, 0, 0, 0, 0, 0);
	      var action = $(e.currentTarget).data('action');
	      var rv = this.actions[action].apply(this, arguments);
	      // 如果是切换面板,及action操作时show开头，则不进行赋值
	      var pattern = /^show/;
	      if(!pattern.test(action)){
		      this.set($(e.currentTarget),this._date);
		      this.fillTime();
		      this.notifyChange();
	      }
	      return rv;
	    },

	    stopEvent: function(e) {
	      e.stopPropagation();
	      e.preventDefault();
	    },

	    // part of the following code was taken from
	    // http://cloud.github.com/downloads/digitalBush/jquery.maskedinput/jquery.maskedinput-1.3.js
	    keydown: function(e) {
	      var self = this, k = e.which, input = $(e.target);
	      if (k == 8 || k == 46) {
	        // backspace and delete cause the maskPosition
	        // to be recalculated
	        setTimeout(function() {
	          self._resetMaskPos(input);
	        });
	      }
	    },

	    keypress: function(e) {
	      var k = e.which;
	      if (k == 8 || k == 46) {
	        // For those browsers which will trigger
	        // keypress on backspace/delete
	        return;
	      }
	      var input = $(e.target);
	      var c = String.fromCharCode(k);
	      var val = input.val() || '';
	      val += c;
	      var mask = this._mask[this._maskPos];
	      if (!mask) {
	        return false;
	      }
	      if (mask.end != val.length) {
	        return;
	      }
	      if (!mask.pattern.test(val.slice(mask.start))) {
	        val = val.slice(0, val.length - 1);
	        while ((mask = this._mask[this._maskPos]) && mask.character) {
	          val += mask.character;
	          // advance mask position past static
	          // part
	          this._maskPos++;
	        }
	        val += c;
	        if (mask.end != val.length) {
	          input.val(val);
	          return false;
	        } else {
	          if (!mask.pattern.test(val.slice(mask.start))) {
	            input.val(val.slice(0, mask.start));
	            return false;
	          } else {
	            input.val(val);
	            this._maskPos++;
	            return false;
	          }
	        }
	      } else {
	        this._maskPos++;
	      }
	    },

	    change: function(e) {
	      var input = $(e.target);
	      var val = input.val();
	      if (this._formatPattern.test(val)) {
	        this.update();
	        this.setValue(this._date.getTime());
	        this.notifyChange();
	        this.set();
	      } else if (val && val.trim()) {
	        this.setValue(this._date.getTime());
	        if (this._date) this.set();
	        else input.val('');
	      } else {
	        if (this._date) {
	          this.setValue(null);
	          // unset the date when the input is
	          // erased
	          this.notifyChange();
	          this._unset = true;
	        }
	      }
	      this._resetMaskPos(input);
	    },
	    //zhanghuan
	    creatmodemonth:function(type){
	    	var month,
	    		year,
	    		day;
	    	if(type){
	    		month = this.viewDate.getUTCMonth()+1;
	    		year = this.viewDate.getUTCFullYear();
    			day = this.viewDate.getUTCDate();
	    	}else{
	    		month = this.viewDate2.getUTCMonth()+1;
	    		year = this.viewDate2.getUTCFullYear();
    			day = this.viewDate2.getUTCDate();
	    	}
	    	if($(".manydate-show-month").length==0){
	    		var t = '<div class="manydate-show-month manydate-show">'+
	    				'<table class="table-condensed">'+
	    				'<thead><tr>'+
	    				'<th class="prev">‹</th><th colspan="5" class="switch">2014</th><th class="next">›</th>'+
	    				'</tr></thead><tbody>'+
	    				'<tr><td colspan="7">'+
	    				'<span class="month">一月</span><span class="month">二月</span><span class="month">三月</span>'+
	    				'<span class="month">四月</span><span class="month">五月</span><span class="month">六月</span>'+
	    				'<span class="month">七月</span><span class="month">八月</span><span class="month">九月</span>'+
	    				'<span class="month">十月</span><span class="month">十一月</span><span class="month">十二月</span>'+
	    				'</td></tr></tbody></table></div>';
	    		$('body').append(t);
	    	}
	    	$(".manydate-show-month").find('th').eq(1).html(year);
	    	$(".manydate-show-month").attr('currentM',month).attr('currentY',year);
	    	$(".manydate-show-month").find('td span').removeClass('active');
	    	$(".manydate-show-month").find('td span').eq(month-1).addClass('active');
	    	this.bindmonthevent();
	    	return $(".manydate-show-month");
	    	
	    	
	    },
	    bindmonthevent:function(){
	    	var that = this;
	    	$(".manydate-show-month").unbind('click.zhanghuan').bind('click.zhanghuan',function(e){
	    		var curr = parseInt($(".manydate-show-month").find(".switch").html());
	    		var m = parseInt($(".manydate-show-month").attr('currentM'));
            	var y =parseInt($(".manydate-show-month").attr('currentY'));
            	var n = $(".manydate-show-month").attr('index')=='1' ? true:false;
	    		var target = $(e.target).closest('span, td, th');
	    		 if (target.length === 1) {
	    		          switch(target[0].nodeName.toLowerCase()) {
	    		            case 'th':
	    		              switch(target[0].className) {
	    		                case 'switch':
	    		                  that.manyshowMode(2,n);
	    		                  break;
	    		                case 'prev':
	    		                	$(".manydate-show-month").find(".switch").html(curr-1);
	    		                	if(y==curr-1){
	    		                		$(".manydate-show-month").find('td span').eq(m-1).addClass('active');
	    		                	}else{
	    		                		$(".manydate-show-month").find('td span').eq(m-1).removeClass('active');
	    		                	}
	    		                	break;
	    		                case 'next':
	    		                	$(".manydate-show-month").find(".switch").html(curr+1);
	    		                	if(y==curr+1){
	    		                		$(".manydate-show-month").find('td span').eq(m-1).addClass('active');
	    		                	}else{
	    		                		$(".manydate-show-month").find('td span').eq(m-1).removeClass('active');
	    		                	}
	    		                	break;
	    		              }
	    		              break;
	    		            case 'span':
	    		            	var month = $(".manydate-show-month").find('td span').index(target)+1;
	    		            	var d;
	    		            	if(n){
	    		            		d = that.viewDate.getUTCDate();
	    		            		var v = $(".manydate-show-month").find(".switch").html()+'-'+(month<10 ? '0'+month:month)+'-'+(d<10?'0'+d:d);
	    		            		that.setValue(v+'/',1);
	    		            	}else{
	    		            		d = that.viewDate2.getUTCDate();
	    		            	    var v = $(".manydate-show-month").find(".switch").html()+'-'+(month<10 ? '0'+month:month)+'-'+(d<10?'0'+d:d);
	    		            		that.setValue('/'+v,2);
	    		            	}
//	    		            	that.hide({target:$('body')});
	    		            	$(".manydate-show-month").hide();
	    		            	if(n){
	    		            		that.widget.find(".panel-st > div:first").show();
	    		            	}else{
	    		            		that.widget.find(".panel-nd > div:first").show();
	    		            	}
	    		            	break;
	    		    }
	    		 }
	    	})
	    },
	    creatmodeyear:function(type){
	    	var month,
    		year,
    		day;
	    	if(type){
	    		month = this.viewDate.getUTCMonth()+1;
	    		year = this.viewDate.getUTCFullYear();
				day = this.viewDate.getUTCDate();
	    	}else{
	    		month = this.viewDate2.getUTCMonth()+1;
	    		year = this.viewDate2.getUTCFullYear();
				day = this.viewDate2.getUTCDate();
	    	}
	    	if($(".manydate-show-year").length==0){
	    		var t = '<div class="manydate-show-year manydate-show">'+
	    				'<table class="table-condensed">'+
	    				'<thead><tr>'+
	    				'<th class="prev">‹</th><th colspan="5" class="switch">2014</th><th class="next">›</th>'+
	    				'</tr></thead><tbody>'+
	    				'<tr><td colspan="7">'+
	    				'<span class="year old">2009</span><span class="year">2010</span><span class="year">2011</span>'+
	    				'<span class="year">2012</span><span class="year">2013</span><span class="year">2014</span>'+
	    				'<span class="year">2015</span><span class="year">2016</span><span class="year">2017</span>'+
	    				'<span class="year">2018</span><span class="year">2019</span><span class="year old">2020</span>'+
	    				'</td></tr>'+
	    				'</tbody></table></div>';
	    		$('body').append(t);
	    	}
	    	$(".manydate-show-year").find('th').eq(1).html((year-4)+'-'+(year+5));
	    	$(".manydate-show-year").attr('currentY',year);
	    	$(".manydate-show-year").attr('indexY',year);
	    	$(".manydate-show-year").find('td span').removeClass('active');
	    	this.randeryear(year-4,year);
	    	this.bindyearevent();
	    	return $(".manydate-show-year");
	    	
	    },
	    randeryear:function(year,ac){
	    	var active = arguments.length==2 ? arguments[1] : -1; 
	    	$(".manydate-show-year").find('td span').removeClass('active');
	    	$(".manydate-show-year").find('td span').each(function(i){
	    		$(this).html(year-1+i);
	    		if(year-1+i==ac){
	    			$(this).addClass("active");
	    		}
	    	})
	    },
	    bindyearevent:function(){
	    	var that = this;
	    	$(".manydate-show-year").unbind('click.zhanghuan2').bind('click.zhanghuan2',function(e){
	    		var curr = parseInt($(".manydate-show-year").attr('indexY'));
            	var y =parseInt($(".manydate-show-year").attr('currentY'));
            	var n = $(".manydate-show-year").attr('index')=='1' ? true:false;
	    		var target = $(e.target).closest('span, td, th');
	    		 if (target.length === 1) {
	    		          switch(target[0].nodeName.toLowerCase()) {
	    		            case 'th':
	    		              switch(target[0].className) {
	    		                case 'prev':
	    		                	$(".manydate-show-year").find(".switch").html((curr-10-4)+'-'+(curr-10+5));
	    		                	$(".manydate-show-year").attr('indexY',curr-10);
	    		                	that.randeryear(curr-10-4,y);
	    		                	break;
	    		                case 'next':
	    		                	$(".manydate-show-year").find(".switch").html((curr+10-4)+'-'+(curr+10+5));
	    		                	$(".manydate-show-year").attr('indexY',curr+10)
	    		                	that.randeryear(curr+10-4,y);
	    		                	break;
	    		              }
	    		              break;
	    		            case 'span':
	    		            	var y = target.html();
	    		            	var d,
	    		            		m
	    		            	if(n){
	    		            		d = that.viewDate.getUTCDate();
	    		            		m = that.viewDate.getUTCMonth()+1;
	    		            		var v = y+'-'+(m<10 ? '0'+m:m)+'-'+(d<10?'0'+d:d);
	    		            		that.setValue(v+'/');
	    		            	}else{
	    		            		d = that.viewDate2.getUTCDate();
	    		            		m = that.viewDate2.getUTCMonth()+1;
	    		            		var v = y+'-'+(m<10 ? '0'+m:m)+'-'+(d<10?'0'+d:d);
	    		            		that.setValue('/'+v);
	    		            	}
	    		            	$(".manydate-show-year").hide();
	    		            	if(n){
	    		            		that.widget.find(".panel-st > div:first").show();
	    		            	}else{
	    		            		that.widget.find(".panel-nd > div:first").show();
	    		            	}
	    		            	break;
	    		    }
	    		 }
	    	})
	    
	    },
	    //zhanghuan
	    manyshowMode:function(dir,type){
	    	if($('.manydate-show').length != 0){
	    		$('.manydate-show').hide();
	    	}
	    	var showmode,
	    		left,
	    		top;
		      if(dir==1){
		    	  showmode =  this.creatmodemonth(type);
		      }else if(dir==2){
		    	  showmode =  this.creatmodeyear(type);
		      }
		      if(type){
		    	  left = this.widget.find(".panel-st").offset().left;
		    	  top = this.widget.find(".panel-st").offset().top;
		    	  this.widget.find(".panel-st > div").hide();
		    	  this.widget.find(".panel-nd > div:first").show();
		    	  showmode.attr('index',1);
		    	  showmode.css({
		    		  top:top-3,
		    		  left:left,
		    		  display:'block'
		    	  })
		      }else{
		    	  left = this.widget.find(".panel-nd").offset().left;
		    	  top = this.widget.find(".panel-nd").offset().top;
		    	  this.widget.find(".panel-nd > div").hide();
		    	  this.widget.find(".panel-st > div:first").show();
		    	  showmode.attr('index',2);
		    	  showmode.css({
		    		  top:top-3,
		    		  left:left,
		    		  display:'block'
		    	  })
		      }
	    },
	    showMode: function(dir) {
	      if (dir) {
	        this.viewMode = Math.max(this.minViewMode, Math.min(
	          2, this.viewMode + dir));
	      }

	      this.widget.find('.datepicker > div').hide().filter(
	        '.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show();
		  
	    },

	    destroy: function() {
	      this._detachDatePickerEvents();
	      this._detachDatePickerGlobalEvents();
	      this.widget.remove();
	      this.$element.removeData('datetimepicker');
    	  this.component.removeData('datetimepicker');     
	    },

	    formatDate: function(d) {
	      return this.format.replace(formatReplacer, function(match) {
	        var methodName, property, rv, len = match.length;
	        if (match === 'ms')
	          len = 1;
	        property = dateFormatComponents[match].property
	        if (property === 'Hours12') {
	          rv = d.getUTCHours();
	          if (rv === 0) rv = 12;
	          else if (rv !== 12) rv = rv % 12;
	        } else if (property === 'Period12') {
	          if (d.getUTCHours() >= 12) return 'PM';
	          else return 'AM';
	        } else {
	          methodName = 'get' + property;
	          rv = d[methodName]();
	        }
	        if (methodName === 'getUTCMonth') rv = rv + 1;
	        if (methodName === 'getUTCYear') rv = rv + 1900 - 2000;
	        return padLeft(rv.toString(), len, '0');
	      });
	    },

	    parseDate: function(str) {
	      var match, i, property, methodName, value, parsed = {};
	      if (!(match = this._formatPattern.exec(str)))
	        return null;
	      for (i = 1; i < match.length; i++) {
	        property = this._propertiesByIndex[i];
	        if (!property)
	          continue;
	        value = match[i];
	        if (/^\d+$/.test(value))
	          value = parseInt(value, 10);
	        parsed[property] = value;
	      }
	      return this._finishParsingDate(parsed);
	    },

	    _resetMaskPos: function(input) {
	      var val = input.val();
	      for (var i = 0; i < this._mask.length; i++) {
	        if (this._mask[i].end > val.length) {
	          // If the mask has ended then jump to
	          // the next
	          this._maskPos = i;
	          break;
	        } else if (this._mask[i].end === val.length) {
	          this._maskPos = i + 1;
	          break;
	        }
	      }
	    },

	    _finishParsingDate: function(parsed) {
	      var year, month, date, hours, minutes, seconds, milliseconds;
	      year = parsed.UTCFullYear;
	      if (parsed.UTCYear) year = 2000 + parsed.UTCYear;
	      if (!year) year = 1970;
	      if (parsed.UTCMonth) month = parsed.UTCMonth - 1;
	      else month = 0;
	      date = parsed.UTCDate || 1;
	      hours = parsed.UTCHours || 0;
	      minutes = parsed.UTCMinutes || 0;
	      seconds = parsed.UTCSeconds || 0;
	      milliseconds = parsed.UTCMilliseconds || 0;
	      if (parsed.Hours12) {
	        hours = parsed.Hours12;
	      }
	      if (parsed.Period12) {
	        if (/pm/i.test(parsed.Period12)) {
	          if (hours != 12) hours = (hours + 12) % 24;
	        } else {
	          hours = hours % 12;
	        }
	      }
	      return UTCDate(year, month, date, hours, minutes, seconds, milliseconds);
	    },

	    _compileFormat: function () {
	      var match, component, components = [], mask = [],
	      str = this.format, propertiesByIndex = {}, i = 0, pos = 0;
	      while (match = formatComponent.exec(str)) {
	        component = match[0];
	        if (component in dateFormatComponents) {
	          i++;
	          propertiesByIndex[i] = dateFormatComponents[component].property;
	          components.push('\\s*' + dateFormatComponents[component].getPattern(
	            this) + '\\s*');
	          mask.push({
	            pattern: new RegExp(dateFormatComponents[component].getPattern(
	              this)),
	            property: dateFormatComponents[component].property,
	            start: pos,
	            end: pos += component.length
	          });
	        }
	        else {
	          components.push(escapeRegExp(component));
	          mask.push({
	            pattern: new RegExp(escapeRegExp(component)),
	            character: component,
	            start: pos,
	            end: ++pos
	          });
	        }
	        str = str.slice(component.length);
	      }
	      this._mask = mask;
	      this._maskPos = 0;
	      this._formatPattern = new RegExp(
	        '^\\s*' + components.join('') + '\\s*$');
	      this._propertiesByIndex = propertiesByIndex;
	    },

	    _attachDatePickerEvents: function() {
	      var self = this;
	      // this handles date picker clicks
	      this.widget.on('click', '.datepicker *', $.proxy(this.click, this));
	      // this handles time picker clicks
	      this.widget.on('click', '[data-action]', $.proxy(this.doAction, this));
	      this.widget.on('mousedown', $.proxy(this.stopEvent, this));
	      if (this.pickDate && this.pickTime) {
	        this.widget.on('click.togglePicker', '.accordion-toggle', function(e) {
	          e.stopPropagation();
	          var $this = $(this);
	          var $parent = $this.closest('ul');
	          var expanded = $parent.find('.collapse.in');
	          var closed = $parent.find('.collapse:not(.in)');
	          var complete = function() {
					closed.height('auto');
	          };
	          if (expanded && expanded.length) {
	            var collapseData = expanded.data('collapse');
	            if (collapseData && collapseData.transitioning) return;
//	            expanded.collapse('hide');
//	            closed.collapse('show');
	            expanded.height(expanded.children().height()).height(0).removeClass('in');
				closed.height(closed.children().height()).addClass('in');
				transition ? closed.one(transition.end, complete) : complete()
	            $this.find('i').toggleClass(self.timeIcon + ' ' + self.dateIcon);
	            self.$element.find('.add-on i').toggleClass(self.timeIcon + ' ' + self.dateIcon);
	          }
	        });
	      }
	      if (this.isInput) {
	        this.$element.on({
	          //'focus': $.proxy(this.show, this),
	          'change': $.proxy(this.change, this)
	        });
	        if (this.options.maskInput) {
	          this.$element.on({
	            'keydown': $.proxy(this.keydown, this),
	            'keypress': $.proxy(this.keypress, this)
	          });
	        }
	        if(this.manyDate){
	        	var that = this;
	        	this.$element.off('blur.zhanghuan').on('blur.zhanghuan',function(){
	        		that.manyinputcheck();
	        		// 如果输入域为空，清除相关隐藏域的值
	        		if(that.$element.val() == ''){
	        			var elemParent = $(that.$element).parent();
					    $('.start-input',elemParent).val('').attr('value','');
					    $('.end-input',elemParent).val('').attr('value','');
	        		}
	        	})
	        }else{
		        // 单面板时间 如果是配置了失去焦点隐藏，则输入框失去焦点时，隐藏日期选择框
		        if(this.autoHide){
		        	var that = this;
		        	this.$element.off('blur.zouwencheng').on('blur.zouwencheng',function(){
		        		that.hide();
		        	});
		        }
	        }

	        
	      } else {
	        this.$element.on({
	          'change': $.proxy(this.change, this)
	        }, 'input');
	        if (this.options.maskInput) {
	          this.$element.on({
	            'keydown': $.proxy(this.keydown, this),
	            'keypress': $.proxy(this.keypress, this)
	          }, 'input');
	        }
	        if (this.component){
	          this.component.on('click', $.proxy(this.show, this));
	        } else {
	          this.$element.on('click', $.proxy(this.show, this));
	        }
	      }
	    },

	    _attachDatePickerGlobalEvents: function() {
	    	var that = this;
	      $(window).on(
	        'resize.datetimepicker' + this.id, $.proxy(this.place, this));
//	      if (!this.isInput) {
	        $(document).on(
	          'mousedown.datetimepicker' + this.id, function(e){
	        	  that.hide(e);
	          });
//	      }
	    },

	    _detachDatePickerEvents: function() {
	      this.widget.off('click', '.datepicker *', this.click);
	      this.widget.off('click', '[data-action]');
	      this.widget.off('mousedown', this.stopEvent);
	      if (this.pickDate && this.pickTime) {
	        this.widget.off('click.togglePicker');
	      }
	      if (this.isInput) {
	        this.$element.off({
	          //'focus': this.show,
	          'change': this.change
	        });
	        if (this.options.maskInput) {
	          this.$element.off({
	            'keydown': this.keydown,
	            'keypress': this.keypress
	          });
	        }
	      } else {
	        this.$element.off({
	          'change': this.change
	        }, 'input');
	        if (this.options.maskInput) {
	          this.$element.off({
	            'keydown': this.keydown,
	            'keypress': this.keypress
	          }, 'input');
	        }
	        if (this.component){
	          this.component.off('click', this.show);
	        } else {
	          this.$element.off('click', this.show);
	        }
	      }
	    },

	    _detachDatePickerGlobalEvents: function () {
	      $(window).off('resize.datetimepicker' + this.id);
//	      if (!this.isInput) {
	        $(document).off('mousedown.datetimepicker' + this.id);
//	      }
	    },

	    _isInFixed: function() {
	      if (this.$element) {
	        var parents = this.$element.parents();
	        var inFixed = false;
	        for (var i=0; i<parents.length; i++) {
	            if ($(parents[i]).css('position') == 'fixed') {
	                inFixed = true;
	                break;
	            }
	        };
	        return inFixed;
	      } else {
	        return false;
	      }
	    }
	  };
   
	  $.fn.datetimepicker = function ( option, val ) {
	    return this.each(function () {
	      var $this = $(this),
	      data = $this.data('datetimepicker'),
	      options = typeof option === 'object' && option;
	      if(typeof option=='object'){
	    	  if(option.manyDate){
	    		  $this.attr('placeholder','yyyy-mm-dd/yyyy-mm-dd');
	    		  $this.css('letter-spacing','-0.8px');
	    	  }else{
	    		  $this.attr('placeholder','yyyy-mm-dd');
	    	  }
	      }
	      if (!data) {
	        $this.data('datetimepicker', (data = new DateTimePicker(
	          this, $.extend({}, $.fn.datetimepicker.defaults,options))));
	      }
	      if (typeof option === 'string') data[option](val);
	    });
	  };

	$.fn.datetimepicker.defaults = {
		maskInput : false,
		pickDate : true,
		pickTime : true,
		pick12HourFormat : false,
		pickSeconds : true,
		startDate : -Infinity,
		endDate : Infinity,
		collapse : true,
		changeFun:null
	};
	var transition = (function() {
			var transitionEnd = (function() {
				var el = document.createElement('bootstrap'), transEndEventNames = {
					'WebkitTransition' : 'webkitTransitionEnd',
					'MozTransition' : 'transitionend',
					'OTransition' : 'oTransitionEnd otransitionend',
					'transition' : 'transitionend'
				}, name;
				for (name in transEndEventNames) {
					if (el.style[name] !== undefined) {
						return transEndEventNames[name]
					}
				}
			}());
			return transitionEnd && {
				end : transitionEnd
			};
	})();
	$.fn.datetimepicker.Constructor = DateTimePicker;
	var dpgId = 0;
	var dates = $.fn.datetimepicker.dates = {
		'zh-CN' : {
			days : [ "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日" ],
			daysShort : [ "周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日" ],
			daysMin : [ "日", "一", "二", "三", "四", "五", "六", "日" ],
			months : [ "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月" ],
			monthsShort : [ "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月" ],
			today : "今日"
		}
	};

	  var dateFormatComponents = {
	    dd: {property: 'UTCDate', getPattern: function() { return '(0?[1-9]|[1-2][0-9]|3[0-1])\\b';}},
	    MM: {property: 'UTCMonth', getPattern: function() {return '(0?[1-9]|1[0-2])\\b';}},
	    yy: {property: 'UTCYear', getPattern: function() {return '(\\d{2})\\b'}},
	    yyyy: {property: 'UTCFullYear', getPattern: function() {return '(\\d{4})\\b';}},
	    hh: {property: 'UTCHours', getPattern: function() {return '(0?[0-9]|1[0-9]|2[0-3])\\b';}},
	    mm: {property: 'UTCMinutes', getPattern: function() {return '(0?[0-9]|[1-5][0-9])\\b';}},
	    ss: {property: 'UTCSeconds', getPattern: function() {return '(0?[0-9]|[1-5][0-9])\\b';}},
	    ms: {property: 'UTCMilliseconds', getPattern: function() {return '([0-9]{1,3})\\b';}},
	    HH: {property: 'Hours12', getPattern: function() {return '(0?[1-9]|1[0-2])\\b';}},
	    PP: {property: 'Period12', getPattern: function() {return '(AM|PM|am|pm|Am|aM|Pm|pM)\\b';}}
	  };

	  var keys = [];
	  for (var k in dateFormatComponents) keys.push(k);
	  keys[keys.length - 1] += '\\b';
	  keys.push('.');

	  var formatComponent = new RegExp(keys.join('\\b|'));
	  keys.pop();
	  var formatReplacer = new RegExp(keys.join('\\b|'), 'g');

	  function escapeRegExp(str) {
	    // http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
	    return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
	  }

	  function padLeft(s, l, c) {
	    if (l < s.length) return s;
	    else return Array(l - s.length + 1).join(c || ' ') + s;
	  }

	  function getTemplate(cfg) {
		 var manyDate = cfg.manyDate,
			 timeIcon = cfg.timeIcon,
			 pickDate = cfg.pickDate,
			 pickTime = cfg.pickTime,
			 is12Hours = cfg.is12Hours,
			 showSeconds = cfg.showSeconds,
			 collapse = cfg.collapse;
	    if (pickDate && pickTime) {
	      return (
	        '<div class="ui-hz-widget bootstrap-datetimepicker-widget dropdown-menu">' +
	          '<ul>' +
	            '<li' + (collapse ? ' class="collapse in"' : '') + '>' +
	              '<div class="datepicker">' +
	                DPGlobal.template +
	              '</div>' +
	            '</li>' +
	            '<li class="picker-switch accordion-toggle"><a><i class="' + timeIcon + '"></i></a></li>' +
	            '<li' + (collapse ? ' class="collapse"' : '') + '>' +
	              '<div class="timepicker">' +
	                TPGlobal.getTemplate(is12Hours, showSeconds) +
	              '</div>' +
	            '</li>' +
	          '</ul>' +
	        '</div>'
	      );
	    } else if (pickTime) {
	      return (
	        '<div class="ui-hz-widget bootstrap-datetimepicker-widget dropdown-menu">' +
	          '<div class="timepicker">' +
	            TPGlobal.getTemplate(is12Hours, showSeconds) +
	          '</div>' +
	        '</div>'
	      );
	    }else if(manyDate){
			return(
				'<div class="many-date">' + 
					'<div class="ui-hz-widget bootstrap-datetimepicker-widget dropdown-menu">' +
						  '<ul>' +
							'<li' + (collapse ? ' class="collapse in"' : '') + '>' +
							  '<div class="datepicker panel-st">' +
								DPGlobal.template +
							  '</div>' +
							'</li>' +
							'<li class="picker-switch accordion-toggle"><a><i class="' + timeIcon + '"></i></a></li>' +
							'<li' + (collapse ? ' class="collapse"' : '') + '>' +
							  '<div class="timepicker">' +
								TPGlobal.getTemplate(is12Hours, showSeconds) +
							  '</div>' +
							'</li>' +
						  '</ul>' +
						'</div>' + 
						'<div class="ui-hz-widget bootstrap-datetimepicker-widget dropdown-menu datetimepicker-nd">' +
							 '<ul>' +
								'<li' + (collapse ? ' class="collapse in"' : '') + '>' +
								  '<div class="datepicker panel-nd">' +
									DPGlobal.template2 +
								  '</div>' +
								'</li>' +
								'<li class="picker-switch accordion-toggle"><a><i class="' + timeIcon + '"></i></a></li>' +
								'<li' + (collapse ? ' class="collapse"' : '') + '>' +
								  '<div class="timepicker">' +
									TPGlobal.getTemplate(is12Hours, showSeconds) +
								  '</div>' +
								'</li>' +
							  '</ul>' +
						'</div>' + 
					'</div>'	
			);
		 } else {
	      return (
	        '<div class="ui-hz-widget bootstrap-datetimepicker-widget dropdown-menu">' +
	          '<div class="datepicker">' +
	            DPGlobal.template +
	          '</div>' +
	        '</div>'
	      );
	    }
	  }

	  function UTCDate() {
	    return new Date(Date.UTC.apply(Date, arguments));
	  }

	  var DPGlobal = {
	    modes: [
	      {
	      clsName: 'days',
	      navFnc: 'UTCMonth',
	      navStep: 1
	    },
	    {
	      clsName: 'months',
	      navFnc: 'UTCFullYear',
	      navStep: 1
	    },
	    {
	      clsName: 'years',
	      navFnc: 'UTCFullYear',
	      navStep: 10
	    }],
	    isLeapYear: function (year) {
	      return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0))
	    },
	    getDaysInMonth: function (year, month) {
	      return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]
	    },
	    headTemplate:
	      '<thead>' +
	        '<tr>' +
	          '<th class="prev">&lsaquo;</th>' +
	          '<th colspan="5" class="switch"></th>' +
	          '<th class="next">&rsaquo;</th>' +
	        '</tr>' +
	      '</thead>',
		headTemplate2:
	      '<thead>' +
	        '<tr>' +
	          '<th class="prev2"></th>' +
	          '<th colspan="5" class="switch"></th>' +
	          '<th class="next2"></th>' +
	        '</tr>' +
	      '</thead>',
	    contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>'
	  };
	  DPGlobal.template =
	    '<div class="datepicker-days">' +
	      '<table class="table-condensed">' +
	        DPGlobal.headTemplate +
	        '<tbody></tbody>' +
	      '</table>' +
	    '</div>' +
	    '<div class="datepicker-months">' +
	      '<table class="table-condensed">' +
	        DPGlobal.headTemplate +
	        DPGlobal.contTemplate+
	      '</table>'+
	    '</div>'+
	    '<div class="datepicker-years">'+
	      '<table class="table-condensed">'+
	        DPGlobal.headTemplate+
	        DPGlobal.contTemplate+
	      '</table>'+
	    '</div>';
	   DPGlobal.template2 =
	    '<div class="datepicker-days">' +
	      '<table class="table-condensed">' +
	        DPGlobal.headTemplate2 +
	        '<tbody></tbody>' +
	      '</table>' +
	    '</div>' +
	    '<div class="datepicker-months">' +
	      '<table class="table-condensed">' +
	        DPGlobal.headTemplate2 +
	        DPGlobal.contTemplate+
	      '</table>'+
	    '</div>'+
	    '<div class="datepicker-years">'+
	      '<table class="table-condensed">'+
	        DPGlobal.headTemplate2+
	        DPGlobal.contTemplate+
	      '</table>'+
	    '</div>';
	  var TPGlobal = {
	    hourTemplate: '<span data-action="showHours" data-time-component="hours" class="timepicker-hour"></span>',
	    minuteTemplate: '<span data-action="showMinutes" data-time-component="minutes" class="timepicker-minute"></span>',
	    secondTemplate: '<span data-action="showSeconds" data-time-component="seconds" class="timepicker-second"></span>'
	  };
	  TPGlobal.getTemplate = function(is12Hours, showSeconds) {
	    return (
	    '<div class="timepicker-picker">' +
	      '<table class="table-condensed"' +
	        (is12Hours ? ' data-hour-format="12"' : '') +
	        '>' +
	        '<tr>' +
	          '<td><a href="#" class="btn" data-action="incrementHours"><i class="icon-chevron-up"></i></a></td>' +
	          '<td class="separator"></td>' +
	          '<td><a href="#" class="btn" data-action="incrementMinutes"><i class="icon-chevron-up"></i></a></td>' +
	          (showSeconds ?
	          '<td class="separator"></td>' +
	          '<td><a href="#" class="btn" data-action="incrementSeconds"><i class="icon-chevron-up"></i></a></td>': '')+
	          (is12Hours ? '<td class="separator"></td>' : '') +
	        '</tr>' +
	        '<tr>' +
	          '<td>' + TPGlobal.hourTemplate + '</td> ' +
	          '<td class="separator">:</td>' +
	          '<td>' + TPGlobal.minuteTemplate + '</td> ' +
	          (showSeconds ?
	          '<td class="separator">:</td>' +
	          '<td>' + TPGlobal.secondTemplate + '</td>' : '') +
	          (is12Hours ?
	          '<td class="separator"></td>' +
	          '<td>' +
	          '<button type="button" class="btn btn-primary" data-action="togglePeriod"></button>' +
	          '</td>' : '') +
	        '</tr>' +
	        '<tr>' +
	          '<td><a href="#" class="btn" data-action="decrementHours"><i class="icon-chevron-down"></i></a></td>' +
	          '<td class="separator"></td>' +
	          '<td><a href="#" class="btn" data-action="decrementMinutes"><i class="icon-chevron-down"></i></a></td>' +
	          (showSeconds ?
	          '<td class="separator"></td>' +
	          '<td><a href="#" class="btn" data-action="decrementSeconds"><i class="icon-chevron-down"></i></a></td>': '') +
	          (is12Hours ? '<td class="separator"></td>' : '') +
	        '</tr>' +
	      '</table>' +
	    '</div>' +
	    '<div class="timepicker-hours" data-action="selectHour">' +
	      '<table class="table-condensed">' +
	      '</table>'+
	    '</div>'+
	    '<div class="timepicker-minutes" data-action="selectMinute">' +
	      '<table class="table-condensed">' +
	      '</table>'+
	    '</div>'+
	    (showSeconds ?
	    '<div class="timepicker-seconds" data-action="selectSecond">' +
	      '<table class="table-condensed">' +
	      '</table>'+
	    '</div>': '')
	    );
	  }
})(this);
	// End of DateTimePicker

	// Start of jquery mousewheel
	/*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net)
	 * Licensed under the MIT License (LICENSE.txt).
	 *
	 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
	 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
	 * Thanks to: Seamus Leahy for adding deltaX and deltaY
	 *
	 * Version: 3.0.6
	 * 
	 * Requires: 1.2.2+
	 */
(function() {
	var types = ['DOMMouseScroll', 'mousewheel'];
	
	if ($.event.fixHooks) {
	    for ( var i=types.length; i; ) {
	        $.event.fixHooks[ types[--i] ] = $.event.mouseHooks;
	    }
	}
	
	$.event.special.mousewheel = {
	    setup: function() {
	        if ( this.addEventListener ) {
	            for ( var i=types.length; i; ) {
	                this.addEventListener( types[--i], handler, false );
	            }
	        } else {
	            this.onmousewheel = handler;
	        }
	    },
	    
	    teardown: function() {
	        if ( this.removeEventListener ) {
	            for ( var i=types.length; i; ) {
	                this.removeEventListener( types[--i], handler, false );
	            }
	        } else {
	            this.onmousewheel = null;
	        }
	    }
	};
	
	$.fn.extend({
	    mousewheel: function(fn) {
	        return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
	    },
	    
	    unmousewheel: function(fn) {
	        return this.unbind("mousewheel", fn);
	    }
	});
	
	
	function handler(event) {
	    var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0;
	    event = $.event.fix(orgEvent);
	    event.type = "mousewheel";
	    
	    // Old school scrollwheel delta
	    if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta/120; }
	    if ( orgEvent.detail     ) { delta = -orgEvent.detail/3; }
	    
	    // New school multidimensional scroll (touchpads) deltas
	    deltaY = delta;
	    
	    // Gecko
	    if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
	        deltaY = 0;
	        deltaX = -1*delta;
	    }
	    
	    // Webkit
	    if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; }
	    if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; }
	    
	    // Add event and delta to the front of the arguments
	    args.unshift(event, delta, deltaX, deltaY);
	    
	    return ($.event.dispatch || $.event.handle).apply(this, args);
	}
	// End of jquery mousewheel
	
	// Start of jquery customer scroll
	/*
	 *  == malihu jquery custom scrollbars plugin == 
	 *  version: 2.8.1 
	 *  author: malihu (http://manos.malihu.gr) 
	 *  plugin home: http://manos.malihu.gr/jquery-custom-content-scroller 
	 */

	/*
	 *	Copyright 2010-2013 Manos Malihutsakis 
	 *	
	 *	This program is free software: you can redistribute it and/or modify 
	 *	it under the terms of the GNU General Public License as published by 
	 *	the Free Software Foundation, either version 3 of the License, or 
	 *	any later version. 
	 *	
	 *	This program is distributed in the hope that it will be useful, 
	 *	but WITHOUT ANY WARRANTY; without even the implied warranty of 
	 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 	 *	GNU General Public License for more details. 
	 *	
	 *	You should have received a copy of the GNU General Public License 
	 *	along with this program.  If not, see http://www.gnu.org/licenses/. 
	 */
	/*plugin script*/
	var methods={
		init:function(options){
			var defaults={ 
				set_width:false, /*optional element width: boolean, pixels, percentage*/
				set_height:false, /*optional element height: boolean, pixels, percentage*/
				horizontalScroll:false, /*scroll horizontally: boolean*/
				scrollInertia:950, /*scrolling inertia: integer (milliseconds)*/
				mouseWheel:true, /*mousewheel support: boolean*/
				mouseWheelPixels:"auto", /*mousewheel pixels amount: integer, "auto"*/
				autoDraggerLength:true, /*auto-adjust scrollbar dragger length: boolean*/
				autoHideScrollbar:false, /*auto-hide scrollbar when idle*/
				scrollButtons:{ /*scroll buttons*/
					enable:false, /*scroll buttons support: boolean*/
					scrollType:"continuous", /*scroll buttons scrolling type: "continuous", "pixels"*/
					scrollSpeed:"auto", /*scroll buttons continuous scrolling speed: integer, "auto"*/
					scrollAmount:40 /*scroll buttons pixels scroll amount: integer (pixels)*/
				},
				advanced:{
					updateOnBrowserResize:true, /*update scrollbars on browser resize (for layouts based on percentages): boolean*/
					updateOnContentResize:false, /*auto-update scrollbars on content resize (for dynamic content): boolean*/
					autoExpandHorizontalScroll:false, /*auto-expand width for horizontal scrolling: boolean*/
					autoScrollOnFocus:true, /*auto-scroll on focused elements: boolean*/
					normalizeMouseWheelDelta:false /*normalize mouse-wheel delta (-1/1)*/
				},
				contentTouchScroll:true, /*scrolling by touch-swipe content: boolean*/
				callbacks:{
					onScrollStart:function(){}, /*user custom callback function on scroll start event*/
					onScroll:function(){}, /*user custom callback function on scroll event*/
					onTotalScroll:function(){}, /*user custom callback function on scroll end reached event*/
					onTotalScrollBack:function(){}, /*user custom callback function on scroll begin reached event*/
					onTotalScrollOffset:0, /*scroll end reached offset: integer (pixels)*/
					onTotalScrollBackOffset:0, /*scroll begin reached offset: integer (pixels)*/
					whileScrolling:function(){} /*user custom callback function on scrolling event*/
				},
				theme:"light" /*"light", "dark", "light-2", "dark-2", "light-thick", "dark-thick", "light-thin", "dark-thin"*/
			},
			options=$.extend(true,defaults,options);
			return this.each(function(){
				var $this=$(this);
				/*set element width/height, create markup for custom scrollbars, add classes*/
				if(options.set_width){
					$this.css("width",options.set_width);
				}
				if(options.set_height){
					$this.css("height",options.set_height);
				}
				if(!$(document).data("mCustomScrollbar-index")){
					$(document).data("mCustomScrollbar-index","1");
				}else{
					var mCustomScrollbarIndex=parseInt($(document).data("mCustomScrollbar-index"));
					$(document).data("mCustomScrollbar-index",mCustomScrollbarIndex+1);
				}
				$this.wrapInner("<div class='mCustomScrollBox"+" mCS-"+options.theme+"' id='mCSB_"+$(document).data("mCustomScrollbar-index")+"' style='position:relative; height:100%; overflow:hidden; max-width:100%;' />").addClass("mCustomScrollbar _mCS_"+$(document).data("mCustomScrollbar-index"));
				var mCustomScrollBox=$this.children(".mCustomScrollBox");
				if(options.horizontalScroll){
					mCustomScrollBox.addClass("mCSB_horizontal").wrapInner("<div class='mCSB_h_wrapper' style='position:relative; left:0; width:999999px;' />");
					var mCSB_h_wrapper=mCustomScrollBox.children(".mCSB_h_wrapper");
					mCSB_h_wrapper.wrapInner("<div class='mCSB_container' style='position:absolute; left:0;' />").children(".mCSB_container").css({"width":mCSB_h_wrapper.children().outerWidth(),"position":"relative"}).unwrap();
				}else{
					mCustomScrollBox.wrapInner("<div class='mCSB_container' style='position:relative; top:0;' />");
				}
				var mCSB_container=mCustomScrollBox.children(".mCSB_container");
				if($.support.touch){
					mCSB_container.addClass("mCS_touch");
				}
				mCSB_container.after("<div class='mCSB_scrollTools' style='position:absolute;'><div class='mCSB_draggerContainer'><div class='mCSB_dragger' style='position:absolute;' oncontextmenu='return false;'><div class='mCSB_dragger_bar' style='position:relative;'></div></div><div class='mCSB_draggerRail'></div></div></div>");
				var mCSB_scrollTools=mCustomScrollBox.children(".mCSB_scrollTools"),
					mCSB_draggerContainer=mCSB_scrollTools.children(".mCSB_draggerContainer"),
					mCSB_dragger=mCSB_draggerContainer.children(".mCSB_dragger");
				if(options.horizontalScroll){
					mCSB_dragger.data("minDraggerWidth",mCSB_dragger.width());
				}else{
					mCSB_dragger.data("minDraggerHeight",mCSB_dragger.height());
				}
				if(options.scrollButtons.enable){
					if(options.horizontalScroll){
						mCSB_scrollTools.prepend("<a class='mCSB_buttonLeft' oncontextmenu='return false;'></a>").append("<a class='mCSB_buttonRight' oncontextmenu='return false;'></a>");
					}else{
						mCSB_scrollTools.prepend("<a class='mCSB_buttonUp' oncontextmenu='return false;'></a>").append("<a class='mCSB_buttonDown' oncontextmenu='return false;'></a>");
					}
				}
				/*mCustomScrollBox scrollTop and scrollLeft is always 0 to prevent browser focus scrolling*/
				mCustomScrollBox.bind("scroll",function(){
					if(!$this.is(".mCS_disabled")){ /*native focus scrolling for disabled scrollbars*/
						mCustomScrollBox.scrollTop(0).scrollLeft(0);
					}
				});
				/*store options, global vars/states, intervals*/
				$this.data({
					/*init state*/
					"mCS_Init":true,
					/*instance index*/
					"mCustomScrollbarIndex":$(document).data("mCustomScrollbar-index"),
					/*option parameters*/
					"horizontalScroll":options.horizontalScroll,
					"scrollInertia":options.scrollInertia,
					"scrollEasing":"mcsEaseOut",
					"mouseWheel":options.mouseWheel,
					"mouseWheelPixels":options.mouseWheelPixels,
					"autoDraggerLength":options.autoDraggerLength,
					"autoHideScrollbar":options.autoHideScrollbar,
					"scrollButtons_enable":options.scrollButtons.enable,
					"scrollButtons_scrollType":options.scrollButtons.scrollType,
					"scrollButtons_scrollSpeed":options.scrollButtons.scrollSpeed,
					"scrollButtons_scrollAmount":options.scrollButtons.scrollAmount,
					"autoExpandHorizontalScroll":options.advanced.autoExpandHorizontalScroll,
					"autoScrollOnFocus":options.advanced.autoScrollOnFocus,
					"normalizeMouseWheelDelta":options.advanced.normalizeMouseWheelDelta,
					"contentTouchScroll":options.contentTouchScroll,
					"onScrollStart_Callback":options.callbacks.onScrollStart,
					"onScroll_Callback":options.callbacks.onScroll,
					"onTotalScroll_Callback":options.callbacks.onTotalScroll,
					"onTotalScrollBack_Callback":options.callbacks.onTotalScrollBack,
					"onTotalScroll_Offset":options.callbacks.onTotalScrollOffset,
					"onTotalScrollBack_Offset":options.callbacks.onTotalScrollBackOffset,
					"whileScrolling_Callback":options.callbacks.whileScrolling,
					/*events binding state*/
					"bindEvent_scrollbar_drag":false,
					"bindEvent_content_touch":false,
					"bindEvent_scrollbar_click":false,
					"bindEvent_mousewheel":false,
					"bindEvent_buttonsContinuous_y":false,
					"bindEvent_buttonsContinuous_x":false,
					"bindEvent_buttonsPixels_y":false,
					"bindEvent_buttonsPixels_x":false,
					"bindEvent_focusin":false,
					"bindEvent_autoHideScrollbar":false,
					/*buttons intervals*/
					"mCSB_buttonScrollRight":false,
					"mCSB_buttonScrollLeft":false,
					"mCSB_buttonScrollDown":false,
					"mCSB_buttonScrollUp":false
				});
				/*max-width/max-height*/
				if(options.horizontalScroll){
					if($this.css("max-width")!=="none"){
						if(!options.advanced.updateOnContentResize){ /*needs updateOnContentResize*/
							options.advanced.updateOnContentResize=true;
						}
					}
				}else{
					if($this.css("max-height")!=="none"){
						var percentage=false,maxHeight=parseInt($this.css("max-height"));
						if($this.css("max-height").indexOf("%")>=0){
							percentage=maxHeight,
							maxHeight=$this.parent().height()*percentage/100;
						}
						$this.css("overflow","hidden");
						mCustomScrollBox.css("max-height",maxHeight);
					}
				}
				$this.mCustomScrollbar("update");
				/*window resize fn (for layouts based on percentages)*/
				if(options.advanced.updateOnBrowserResize){
					var mCSB_resizeTimeout,currWinWidth=$(window).width(),currWinHeight=$(window).height();
					$(window).bind("resize."+$this.data("mCustomScrollbarIndex"),function(){
						if(mCSB_resizeTimeout){
							clearTimeout(mCSB_resizeTimeout);
						}
						mCSB_resizeTimeout=setTimeout(function(){
							if(!$this.is(".mCS_disabled") && !$this.is(".mCS_destroyed")){
								var winWidth=$(window).width(),winHeight=$(window).height();
								if(currWinWidth!==winWidth || currWinHeight!==winHeight){ /*ie8 fix*/
									if($this.css("max-height")!=="none" && percentage){
										mCustomScrollBox.css("max-height",$this.parent().height()*percentage/100);
									}
									$this.mCustomScrollbar("update");
									currWinWidth=winWidth; currWinHeight=winHeight;
								}
							}
						},150);
					});
				}
				/*content resize fn (for dynamically generated content)*/
				if(options.advanced.updateOnContentResize){
					var mCSB_onContentResize;
					if(options.horizontalScroll){
						var mCSB_containerOldSize=mCSB_container.outerWidth();
					}else{
						var mCSB_containerOldSize=mCSB_container.outerHeight();
					}
					mCSB_onContentResize=setInterval(function(){
						if(options.horizontalScroll){
							if(options.advanced.autoExpandHorizontalScroll){
								mCSB_container.css({"position":"absolute","width":"auto"}).wrap("<div class='mCSB_h_wrapper' style='position:relative; left:0; width:999999px;' />").css({"width":mCSB_container.outerWidth(),"position":"relative"}).unwrap();
							}
							var mCSB_containerNewSize=mCSB_container.outerWidth();
						}else{
							var mCSB_containerNewSize=mCSB_container.outerHeight();
						}
						if(mCSB_containerNewSize!=mCSB_containerOldSize){
							$this.mCustomScrollbar("update");
							mCSB_containerOldSize=mCSB_containerNewSize;
						}
					},300);
				}
			});
		},
		update:function(){

			var $this=$(this),
				mCustomScrollBox=$this.children(".mCustomScrollBox"),
				mCSB_container=mCustomScrollBox.children(".mCSB_container");
			mCSB_container.removeClass("mCS_no_scrollbar");
			$this.removeClass("mCS_disabled mCS_destroyed");
			mCustomScrollBox.scrollTop(0).scrollLeft(0); /*reset scrollTop/scrollLeft to prevent browser focus scrolling*/
			var mCSB_scrollTools=mCustomScrollBox.children(".mCSB_scrollTools"),
				mCSB_draggerContainer=mCSB_scrollTools.children(".mCSB_draggerContainer"),
				mCSB_dragger=mCSB_draggerContainer.children(".mCSB_dragger");
			
			if($this.data("horizontalScroll")){
				var mCSB_buttonLeft=mCSB_scrollTools.children(".mCSB_buttonLeft"),
					mCSB_buttonRight=mCSB_scrollTools.children(".mCSB_buttonRight"),
					mCustomScrollBoxW=mCustomScrollBox.width();
				if($this.data("autoExpandHorizontalScroll")){
					mCSB_container.css({"position":"absolute","width":"auto"}).wrap("<div class='mCSB_h_wrapper' style='position:relative; left:0; width:999999px;' />").css({"width":mCSB_container.outerWidth(),"position":"relative"}).unwrap();
				}
				var mCSB_containerW=mCSB_container.outerWidth();
			}else{
				var mCSB_buttonUp=mCSB_scrollTools.children(".mCSB_buttonUp"),
					mCSB_buttonDown=mCSB_scrollTools.children(".mCSB_buttonDown"),
					mCustomScrollBoxH=mCustomScrollBox.height(),
					mCSB_containerH=mCSB_container.outerHeight();
			}
			
			if(mCSB_containerH>mCustomScrollBoxH && !$this.data("horizontalScroll")){ /*content needs vertical scrolling*/
				mCSB_scrollTools.css("display","block");
				var mCSB_draggerContainerH=mCSB_draggerContainer.height();
				/*auto adjust scrollbar dragger length analogous to content*/
				if($this.data("autoDraggerLength")){
					var draggerH=Math.round(mCustomScrollBoxH/mCSB_containerH*mCSB_draggerContainerH),
						minDraggerH=mCSB_dragger.data("minDraggerHeight");
					if(draggerH<=minDraggerH){ /*min dragger height*/
						mCSB_dragger.css({"height":minDraggerH});
					}else if(draggerH>=mCSB_draggerContainerH-10){ /*max dragger height*/
						var mCSB_draggerContainerMaxH=mCSB_draggerContainerH-10;
						mCSB_dragger.css({"height":mCSB_draggerContainerMaxH});
					}else{
						mCSB_dragger.css({"height":draggerH});
					}
					mCSB_dragger.children(".mCSB_dragger_bar").css({"line-height":mCSB_dragger.height()+"px"});
				}
				var mCSB_draggerH=mCSB_dragger.height(),
				/*calculate and store scroll amount, add scrolling*/
					scrollAmount=(mCSB_containerH-mCustomScrollBoxH)/(mCSB_draggerContainerH-mCSB_draggerH);
				$this.data("scrollAmount",scrollAmount).mCustomScrollbar("scrolling",mCustomScrollBox,mCSB_container,mCSB_draggerContainer,mCSB_dragger,mCSB_buttonUp,mCSB_buttonDown,mCSB_buttonLeft,mCSB_buttonRight);
				/*scroll*/
				var mCSB_containerP=Math.abs(mCSB_container.position().top);
				$this.mCustomScrollbar("scrollTo",mCSB_containerP,{scrollInertia:0,trigger:"internal"});
			}else if(mCSB_containerW>mCustomScrollBoxW && $this.data("horizontalScroll")){ /*content needs horizontal scrolling*/
				mCSB_scrollTools.css("display","block");
				var mCSB_draggerContainerW=mCSB_draggerContainer.width();
				/*auto adjust scrollbar dragger length analogous to content*/
				if($this.data("autoDraggerLength")){
					var draggerW=Math.round(mCustomScrollBoxW/mCSB_containerW*mCSB_draggerContainerW),
						minDraggerW=mCSB_dragger.data("minDraggerWidth");
					if(draggerW<=minDraggerW){ /*min dragger height*/
						mCSB_dragger.css({"width":minDraggerW});
					}else if(draggerW>=mCSB_draggerContainerW-10){ /*max dragger height*/
						var mCSB_draggerContainerMaxW=mCSB_draggerContainerW-10;
						mCSB_dragger.css({"width":mCSB_draggerContainerMaxW});
					}else{
						mCSB_dragger.css({"width":draggerW});
					}
				}
				var mCSB_draggerW=mCSB_dragger.width(),
				/*calculate and store scroll amount, add scrolling*/
					scrollAmount=(mCSB_containerW-mCustomScrollBoxW)/(mCSB_draggerContainerW-mCSB_draggerW);
				$this.data("scrollAmount",scrollAmount).mCustomScrollbar("scrolling",mCustomScrollBox,mCSB_container,mCSB_draggerContainer,mCSB_dragger,mCSB_buttonUp,mCSB_buttonDown,mCSB_buttonLeft,mCSB_buttonRight);
				/*scroll*/
				var mCSB_containerP=Math.abs(mCSB_container.position().left);
				$this.mCustomScrollbar("scrollTo",mCSB_containerP,{scrollInertia:0,trigger:"internal"});
			}else{ /*content does not need scrolling*/
				/*unbind events, reset content position, hide scrollbars, remove classes*/
				mCustomScrollBox.unbind("mousewheel focusin");
				if($this.data("horizontalScroll")){
					mCSB_dragger.add(mCSB_container).css("left",0);
				}else{
					mCSB_dragger.add(mCSB_container).css("top",0);
				}
				mCSB_scrollTools.css("display","none");
				mCSB_container.addClass("mCS_no_scrollbar");
				$this.data({"bindEvent_mousewheel":false,"bindEvent_focusin":false});
			}
			
		},
		scrolling:function(mCustomScrollBox,mCSB_container,mCSB_draggerContainer,mCSB_dragger,mCSB_buttonUp,mCSB_buttonDown,mCSB_buttonLeft,mCSB_buttonRight){
			var $this=$(this);
			/*scrollbar drag scrolling*/
			if(!$this.data("bindEvent_scrollbar_drag")){
				var mCSB_draggerDragY,mCSB_draggerDragX;
				if($.support.msPointer){ /*MSPointer*/
					mCSB_dragger.bind("MSPointerDown",function(e){
						e.preventDefault();
						$this.data({"on_drag":true}); mCSB_dragger.addClass("mCSB_dragger_onDrag");
						var elem=$(this),
							elemOffset=elem.offset(),
							x=e.originalEvent.pageX-elemOffset.left,
							y=e.originalEvent.pageY-elemOffset.top;
						if(x<elem.width() && x>0 && y<elem.height() && y>0){
							mCSB_draggerDragY=y;
							mCSB_draggerDragX=x;
						}
					});
					$(document).bind("MSPointerMove."+$this.data("mCustomScrollbarIndex"),function(e){
						e.preventDefault();
						if($this.data("on_drag")){
							var elem=mCSB_dragger,
								elemOffset=elem.offset(),
								x=e.originalEvent.pageX-elemOffset.left,
								y=e.originalEvent.pageY-elemOffset.top;
							scrollbarDrag(mCSB_draggerDragY,mCSB_draggerDragX,y,x);
						}
					}).bind("MSPointerUp."+$this.data("mCustomScrollbarIndex"),function(e){
						$this.data({"on_drag":false}); mCSB_dragger.removeClass("mCSB_dragger_onDrag");
					});
				}else{ /*mouse/touch*/
					mCSB_dragger.bind("mousedown touchstart",function(e){
						/*for bug -------------by--zhanghuan*/
						var id = $(e.target).closest("div[id^=mCSB]").attr('id');
						$('.tip-container[scrollbar='+id+']').hide();
						
						$('.bootstrap-datetimepicker-widget').each(function(i){
							if($(this).parent().hasClass('many-date')){
								$(this).parent().hide();
							}else{
								$(this).hide();
							}
						})
						if($(e.target).closest(".ui-slide-choose").length==0){
							$('.ui-slide-choose').removeClass('ui-slide-choose-open');
						}

						
						e.preventDefault(); e.stopImmediatePropagation();
						var	elem=$(this),elemOffset=elem.offset(),x,y;
						if(e.type==="touchstart"){
							var touch=e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
							x=touch.pageX-elemOffset.left; y=touch.pageY-elemOffset.top;
						}else{
							$this.data({"on_drag":true}); mCSB_dragger.addClass("mCSB_dragger_onDrag");
							x=e.pageX-elemOffset.left; y=e.pageY-elemOffset.top;
						}
						if(x<elem.width() && x>0 && y<elem.height() && y>0){
							mCSB_draggerDragY=y; mCSB_draggerDragX=x;
						}
					}).bind("touchmove",function(e){
						e.preventDefault(); e.stopImmediatePropagation();
						var touch=e.originalEvent.touches[0] || e.originalEvent.changedTouches[0],
							elem=$(this),
							elemOffset=elem.offset(),
							x=touch.pageX-elemOffset.left,
							y=touch.pageY-elemOffset.top;
						scrollbarDrag(mCSB_draggerDragY,mCSB_draggerDragX,y,x);
					});
					$(document).bind("mousemove."+$this.data("mCustomScrollbarIndex"),function(e){
						if($this.data("on_drag")){
							var elem=mCSB_dragger,
								elemOffset=elem.offset(),
								x=e.pageX-elemOffset.left,
								y=e.pageY-elemOffset.top;
							scrollbarDrag(mCSB_draggerDragY,mCSB_draggerDragX,y,x);
						}
					}).bind("mouseup."+$this.data("mCustomScrollbarIndex"),function(e){
						$this.data({"on_drag":false}); mCSB_dragger.removeClass("mCSB_dragger_onDrag");
					});
				}
				$this.data({"bindEvent_scrollbar_drag":true});
			}
			function scrollbarDrag(mCSB_draggerDragY,mCSB_draggerDragX,y,x){
				if($this.data("horizontalScroll")){
					$this.mCustomScrollbar("scrollTo",(mCSB_dragger.position().left-(mCSB_draggerDragX))+x,{moveDragger:true,trigger:"internal"});
				}else{
					$this.mCustomScrollbar("scrollTo",(mCSB_dragger.position().top-(mCSB_draggerDragY))+y,{moveDragger:true,trigger:"internal"});
				}
			}
			/*content touch-drag*/
			if($.support.touch && $this.data("contentTouchScroll")){
				if(!$this.data("bindEvent_content_touch")){
					var touch,
						elem,elemOffset,y,x,mCSB_containerTouchY,mCSB_containerTouchX;
					mCSB_container.bind("touchstart",function(e){
						e.stopImmediatePropagation();
						touch=e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
						elem=$(this);
						elemOffset=elem.offset();
						x=touch.pageX-elemOffset.left;
						y=touch.pageY-elemOffset.top;
						mCSB_containerTouchY=y;
						mCSB_containerTouchX=x;
					});
					mCSB_container.bind("touchmove",function(e){
						e.preventDefault(); e.stopImmediatePropagation();
						touch=e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
						elem=$(this).parent();
						elemOffset=elem.offset();
						x=touch.pageX-elemOffset.left;
						y=touch.pageY-elemOffset.top;
						if($this.data("horizontalScroll")){
							$this.mCustomScrollbar("scrollTo",mCSB_containerTouchX-x,{trigger:"internal"});
						}else{
							$this.mCustomScrollbar("scrollTo",mCSB_containerTouchY-y,{trigger:"internal"});
						}
					});
				}
			}
			/*dragger rail click scrolling*/
			if(!$this.data("bindEvent_scrollbar_click")){
				mCSB_draggerContainer.bind("click",function(e){
					var scrollToPos=(e.pageY-mCSB_draggerContainer.offset().top)*$this.data("scrollAmount"),target=$(e.target);
					if($this.data("horizontalScroll")){
						scrollToPos=(e.pageX-mCSB_draggerContainer.offset().left)*$this.data("scrollAmount");
					}
					if(target.hasClass("mCSB_draggerContainer") || target.hasClass("mCSB_draggerRail")){
						$this.mCustomScrollbar("scrollTo",scrollToPos,{trigger:"internal",scrollEasing:"draggerRailEase"});
					}
				});
				$this.data({"bindEvent_scrollbar_click":true});
			}
			/*mousewheel scrolling*/
			if($this.data("mouseWheel")){
				if(!$this.data("bindEvent_mousewheel")){
					mCustomScrollBox.bind("mousewheel",function(e,delta){
						/*********creat by zhanghuan*************/
						var id = $(e.target).closest("div[id^=mCSB]").attr('id');
						$('.tip-container[scrollbar='+id+']').hide();
						
						$('.bootstrap-datetimepicker-widget').each(function(i){
							if($(this).parent().hasClass('many-date')){
								$(this).parent().hide();
							}else{
								$(this).hide();
							}
						})
						if($(e.target).closest(".ui-slide-choose").length==0){
							$('.ui-slide-choose').removeClass('ui-slide-choose-open');
						}
						
						var scrollTo,mouseWheelPixels=$this.data("mouseWheelPixels"),absPos=Math.abs(mCSB_container.position().top),
							draggerPos=mCSB_dragger.position().top,limit=mCSB_draggerContainer.height()-mCSB_dragger.height();
						if($this.data("normalizeMouseWheelDelta")){
							if(delta<0){delta=-1;}else{delta=1;}
						}
						if(mouseWheelPixels==="auto"){
							mouseWheelPixels=100+Math.round($this.data("scrollAmount")/2);
						}
						if($this.data("horizontalScroll")){
							draggerPos=mCSB_dragger.position().left; 
							limit=mCSB_draggerContainer.width()-mCSB_dragger.width();
							absPos=Math.abs(mCSB_container.position().left);
						}
						if((delta>0 && draggerPos!==0) || (delta<0 && draggerPos!==limit)){e.preventDefault(); e.stopImmediatePropagation();}
						scrollTo=absPos-(delta*mouseWheelPixels);
						$this.mCustomScrollbar("scrollTo",scrollTo,{trigger:"internal"});
					});
					$this.data({"bindEvent_mousewheel":true});
				}
			}
			/*buttons scrolling*/
			if($this.data("scrollButtons_enable")){
				if($this.data("scrollButtons_scrollType")==="pixels"){ /*scroll by pixels*/
					if($this.data("horizontalScroll")){
						mCSB_buttonRight.add(mCSB_buttonLeft).unbind("mousedown touchstart MSPointerDown mouseup MSPointerUp mouseout MSPointerOut touchend",mCSB_buttonRight_stop,mCSB_buttonLeft_stop);
						$this.data({"bindEvent_buttonsContinuous_x":false});
						if(!$this.data("bindEvent_buttonsPixels_x")){
							/*scroll right*/
							mCSB_buttonRight.bind("click",function(e){
								e.preventDefault();
								PixelsScrollTo(Math.abs(mCSB_container.position().left)+$this.data("scrollButtons_scrollAmount"));
							});
							/*scroll left*/
							mCSB_buttonLeft.bind("click",function(e){
								e.preventDefault();
								PixelsScrollTo(Math.abs(mCSB_container.position().left)-$this.data("scrollButtons_scrollAmount"));
							});
							$this.data({"bindEvent_buttonsPixels_x":true});
						}
					}else{
						mCSB_buttonDown.add(mCSB_buttonUp).unbind("mousedown touchstart MSPointerDown mouseup MSPointerUp mouseout MSPointerOut touchend",mCSB_buttonRight_stop,mCSB_buttonLeft_stop);
						$this.data({"bindEvent_buttonsContinuous_y":false});
						if(!$this.data("bindEvent_buttonsPixels_y")){
							/*scroll down*/
							mCSB_buttonDown.bind("click",function(e){
								e.preventDefault();
								PixelsScrollTo(Math.abs(mCSB_container.position().top)+$this.data("scrollButtons_scrollAmount"));
							});
							/*scroll up*/
							mCSB_buttonUp.bind("click",function(e){
								e.preventDefault();
								PixelsScrollTo(Math.abs(mCSB_container.position().top)-$this.data("scrollButtons_scrollAmount"));
							});
							$this.data({"bindEvent_buttonsPixels_y":true});
						}
					}
					function PixelsScrollTo(to){
						if(!mCSB_dragger.data("preventAction")){
							mCSB_dragger.data("preventAction",true);
							$this.mCustomScrollbar("scrollTo",to,{trigger:"internal"});
						}
					}
				}else{ /*continuous scrolling*/
					if($this.data("horizontalScroll")){
						mCSB_buttonRight.add(mCSB_buttonLeft).unbind("click");
						$this.data({"bindEvent_buttonsPixels_x":false});
						if(!$this.data("bindEvent_buttonsContinuous_x")){
							/*scroll right*/
							mCSB_buttonRight.bind("mousedown touchstart MSPointerDown",function(e){
								e.preventDefault();
								var scrollButtonsSpeed=ScrollButtonsSpeed();
								$this.data({"mCSB_buttonScrollRight":setInterval(function(){
									$this.mCustomScrollbar("scrollTo",Math.abs(mCSB_container.position().left)+scrollButtonsSpeed,{trigger:"internal",scrollEasing:"easeOutCirc"});
								},17)});
							});
							var mCSB_buttonRight_stop=function(e){
								e.preventDefault(); clearInterval($this.data("mCSB_buttonScrollRight"));
							}
							mCSB_buttonRight.bind("mouseup touchend MSPointerUp mouseout MSPointerOut",mCSB_buttonRight_stop);
							/*scroll left*/
							mCSB_buttonLeft.bind("mousedown touchstart MSPointerDown",function(e){
								e.preventDefault();
								var scrollButtonsSpeed=ScrollButtonsSpeed();
								$this.data({"mCSB_buttonScrollLeft":setInterval(function(){
									$this.mCustomScrollbar("scrollTo",Math.abs(mCSB_container.position().left)-scrollButtonsSpeed,{trigger:"internal",scrollEasing:"easeOutCirc"});
								},17)});
							});	
							var mCSB_buttonLeft_stop=function(e){
								e.preventDefault(); clearInterval($this.data("mCSB_buttonScrollLeft"));
							}
							mCSB_buttonLeft.bind("mouseup touchend MSPointerUp mouseout MSPointerOut",mCSB_buttonLeft_stop);
							$this.data({"bindEvent_buttonsContinuous_x":true});
						}
					}else{
						mCSB_buttonDown.add(mCSB_buttonUp).unbind("click");
						$this.data({"bindEvent_buttonsPixels_y":false});
						if(!$this.data("bindEvent_buttonsContinuous_y")){
							/*scroll down*/
							mCSB_buttonDown.bind("mousedown touchstart MSPointerDown",function(e){
								e.preventDefault();
								var scrollButtonsSpeed=ScrollButtonsSpeed();
								$this.data({"mCSB_buttonScrollDown":setInterval(function(){
									$this.mCustomScrollbar("scrollTo",Math.abs(mCSB_container.position().top)+scrollButtonsSpeed,{trigger:"internal",scrollEasing:"easeOutCirc"});
								},17)});
							});
							var mCSB_buttonDown_stop=function(e){
								e.preventDefault(); clearInterval($this.data("mCSB_buttonScrollDown"));
							}
							mCSB_buttonDown.bind("mouseup touchend MSPointerUp mouseout MSPointerOut",mCSB_buttonDown_stop);
							/*scroll up*/
							mCSB_buttonUp.bind("mousedown touchstart MSPointerDown",function(e){
								e.preventDefault();
								var scrollButtonsSpeed=ScrollButtonsSpeed();
								$this.data({"mCSB_buttonScrollUp":setInterval(function(){
									$this.mCustomScrollbar("scrollTo",Math.abs(mCSB_container.position().top)-scrollButtonsSpeed,{trigger:"internal",scrollEasing:"easeOutCirc"});
								},17)});
							});	
							var mCSB_buttonUp_stop=function(e){
								e.preventDefault(); clearInterval($this.data("mCSB_buttonScrollUp"));
							}
							mCSB_buttonUp.bind("mouseup touchend MSPointerUp mouseout MSPointerOut",mCSB_buttonUp_stop);
							$this.data({"bindEvent_buttonsContinuous_y":true});
						}
					}
					function ScrollButtonsSpeed(){
						var speed=$this.data("scrollButtons_scrollSpeed");
						if($this.data("scrollButtons_scrollSpeed")==="auto"){
							speed=Math.round(($this.data("scrollInertia")+100)/40);
						}
						return speed;
					}
				}
			}
			/*scrolling on element focus (e.g. via TAB key)*/
			if($this.data("autoScrollOnFocus")){
				if(!$this.data("bindEvent_focusin")){
					mCustomScrollBox.bind("focusin",function(){
						mCustomScrollBox.scrollTop(0).scrollLeft(0);
						var focusedElem=$(document.activeElement);
						if(focusedElem.is("input,textarea,select,button,a[tabindex],area,object")){
							var mCSB_containerPos=mCSB_container.position().top,
								focusedElemPos=focusedElem.position().top,
								visibleLimit=mCustomScrollBox.height()-focusedElem.outerHeight();
							if($this.data("horizontalScroll")){
								mCSB_containerPos=mCSB_container.position().left;
								focusedElemPos=focusedElem.position().left;
								visibleLimit=mCustomScrollBox.width()-focusedElem.outerWidth();
							}
							if(mCSB_containerPos+focusedElemPos<0 || mCSB_containerPos+focusedElemPos>visibleLimit){
								$this.mCustomScrollbar("scrollTo",focusedElemPos,{trigger:"internal"});
							}
						}
					});
					$this.data({"bindEvent_focusin":true});
				}
			}
			/*auto-hide scrollbar*/
			if($this.data("autoHideScrollbar")){
				if(!$this.data("bindEvent_autoHideScrollbar")){
					mCustomScrollBox.bind("mouseenter",function(e){
						mCustomScrollBox.addClass("mCS-mouse-over");
						functions.showScrollbar.call(mCustomScrollBox.children(".mCSB_scrollTools"));
					}).bind("mouseleave touchend",function(e){
						mCustomScrollBox.removeClass("mCS-mouse-over");
						if(e.type==="mouseleave"){functions.hideScrollbar.call(mCustomScrollBox.children(".mCSB_scrollTools"));}
					});
					$this.data({"bindEvent_autoHideScrollbar":true});
				}
			}
		},
		scrollTo:function(scrollTo,options){
			var $this=$(this),
				defaults={
					moveDragger:false,
					trigger:"external",
					callbacks:true,
					scrollInertia:$this.data("scrollInertia"),
					scrollEasing:$this.data("scrollEasing")
				},
				options=$.extend(defaults,options),
				draggerScrollTo,
				mCustomScrollBox=$this.children(".mCustomScrollBox"),
				mCSB_container=mCustomScrollBox.children(".mCSB_container"),
				mCSB_scrollTools=mCustomScrollBox.children(".mCSB_scrollTools"),
				mCSB_draggerContainer=mCSB_scrollTools.children(".mCSB_draggerContainer"),
				mCSB_dragger=mCSB_draggerContainer.children(".mCSB_dragger"),
				contentSpeed=draggerSpeed=options.scrollInertia,
				scrollBeginning,scrollBeginningOffset,totalScroll,totalScrollOffset;
			if(!mCSB_container.hasClass("mCS_no_scrollbar")){
				$this.data({"mCS_trigger":options.trigger});
				if($this.data("mCS_Init")){options.callbacks=false;}
				if(scrollTo || scrollTo===0){
					if(typeof(scrollTo)==="number"){ /*if integer, scroll by number of pixels*/
						if(options.moveDragger){ /*scroll dragger*/
							draggerScrollTo=scrollTo;
							if($this.data("horizontalScroll")){
								scrollTo=mCSB_dragger.position().left*$this.data("scrollAmount");
							}else{
								scrollTo=mCSB_dragger.position().top*$this.data("scrollAmount");
							}
							draggerSpeed=0;
						}else{ /*scroll content by default*/
							draggerScrollTo=scrollTo/$this.data("scrollAmount");
						}
					}else if(typeof(scrollTo)==="string"){ /*if string, scroll by element position*/
						var target;
						if(scrollTo==="top"){ /*scroll to top*/
							target=0;
						}else if(scrollTo==="bottom" && !$this.data("horizontalScroll")){ /*scroll to bottom*/
							target=mCSB_container.outerHeight()-mCustomScrollBox.height();
						}else if(scrollTo==="left"){ /*scroll to left*/
							target=0;
						}else if(scrollTo==="right" && $this.data("horizontalScroll")){ /*scroll to right*/
							target=mCSB_container.outerWidth()-mCustomScrollBox.width();
						}else if(scrollTo==="first"){ /*scroll to first element position*/
							target=$this.find(".mCSB_container").find(":first");
						}else if(scrollTo==="last"){ /*scroll to last element position*/
							target=$this.find(".mCSB_container").find(":last");
						}else{ /*scroll to element position*/
							target=$this.find(scrollTo);
						}
						if(target.length===1){ /*if such unique element exists, scroll to it*/
							if($this.data("horizontalScroll")){
								scrollTo=target.position().left;
							}else{
								scrollTo=target.position().top;
							}
							draggerScrollTo=scrollTo/$this.data("scrollAmount");
						}else{
							draggerScrollTo=scrollTo=target;
						}
					}
					/*scroll to*/
					if($this.data("horizontalScroll")){
						if($this.data("onTotalScrollBack_Offset")){ /*scroll beginning offset*/
							scrollBeginningOffset=-$this.data("onTotalScrollBack_Offset");
						}
						if($this.data("onTotalScroll_Offset")){ /*total scroll offset*/
							totalScrollOffset=mCustomScrollBox.width()-mCSB_container.outerWidth()+$this.data("onTotalScroll_Offset");
						}
						if(draggerScrollTo<0){ /*scroll start position*/
							draggerScrollTo=scrollTo=0; clearInterval($this.data("mCSB_buttonScrollLeft"));
							if(!scrollBeginningOffset){scrollBeginning=true;}
						}else if(draggerScrollTo>=mCSB_draggerContainer.width()-mCSB_dragger.width()){ /*scroll end position*/
							draggerScrollTo=mCSB_draggerContainer.width()-mCSB_dragger.width();
							scrollTo=mCustomScrollBox.width()-mCSB_container.outerWidth(); clearInterval($this.data("mCSB_buttonScrollRight"));
							if(!totalScrollOffset){totalScroll=true;}
						}else{scrollTo=-scrollTo;}
						/*scrolling animation*/
						functions.mTweenAxis.call(this,mCSB_dragger[0],"left",Math.round(draggerScrollTo),draggerSpeed,options.scrollEasing);
						functions.mTweenAxis.call(this,mCSB_container[0],"left",Math.round(scrollTo),contentSpeed,options.scrollEasing,{
							onStart:function(){
								if(options.callbacks && !$this.data("mCS_tweenRunning")){callbacks("onScrollStart");}
								if($this.data("autoHideScrollbar")){functions.showScrollbar.call(mCSB_scrollTools);}
							},
							onUpdate:function(){
								if(options.callbacks){callbacks("whileScrolling");}
							},
							onComplete:function(){
								if(options.callbacks){
									callbacks("onScroll");
									if(scrollBeginning || (scrollBeginningOffset && mCSB_container.position().left>=scrollBeginningOffset)){callbacks("onTotalScrollBack");}
									if(totalScroll || (totalScrollOffset && mCSB_container.position().left<=totalScrollOffset)){callbacks("onTotalScroll");}
								}
								mCSB_dragger.data("preventAction",false); $this.data("mCS_tweenRunning",false);
								if($this.data("autoHideScrollbar")){if(!mCustomScrollBox.hasClass("mCS-mouse-over")){functions.hideScrollbar.call(mCSB_scrollTools);}}
							}
						});
					}else{
						if($this.data("onTotalScrollBack_Offset")){ /*scroll beginning offset*/
							scrollBeginningOffset=-$this.data("onTotalScrollBack_Offset");
						}
						if($this.data("onTotalScroll_Offset")){ /*total scroll offset*/
							totalScrollOffset=mCustomScrollBox.height()-mCSB_container.outerHeight()+$this.data("onTotalScroll_Offset");
						}
						if(draggerScrollTo<0){ /*scroll start position*/
							draggerScrollTo=scrollTo=0; clearInterval($this.data("mCSB_buttonScrollUp"));
							if(!scrollBeginningOffset){scrollBeginning=true;}
						}else if(draggerScrollTo>=mCSB_draggerContainer.height()-mCSB_dragger.height()){ /*scroll end position*/
							draggerScrollTo=mCSB_draggerContainer.height()-mCSB_dragger.height();
							scrollTo=mCustomScrollBox.height()-mCSB_container.outerHeight(); clearInterval($this.data("mCSB_buttonScrollDown"));
							if(!totalScrollOffset){totalScroll=true;}
						}else{scrollTo=-scrollTo;}
						/*scrolling animation*/
						functions.mTweenAxis.call(this,mCSB_dragger[0],"top",Math.round(draggerScrollTo),draggerSpeed,options.scrollEasing);
						functions.mTweenAxis.call(this,mCSB_container[0],"top",Math.round(scrollTo),contentSpeed,options.scrollEasing,{
							onStart:function(){
								if(options.callbacks && !$this.data("mCS_tweenRunning")){callbacks("onScrollStart");}
								if($this.data("autoHideScrollbar")){functions.showScrollbar.call(mCSB_scrollTools);}
							},
							onUpdate:function(){
								if(options.callbacks){callbacks("whileScrolling");}
							},
							onComplete:function(){
								if(options.callbacks){
									callbacks("onScroll");
									if(scrollBeginning || (scrollBeginningOffset && mCSB_container.position().top>=scrollBeginningOffset)){callbacks("onTotalScrollBack");}
									if(totalScroll || (totalScrollOffset && mCSB_container.position().top<=totalScrollOffset)){callbacks("onTotalScroll");}
								}
								mCSB_dragger.data("preventAction",false); $this.data("mCS_tweenRunning",false);
								if($this.data("autoHideScrollbar")){if(!mCustomScrollBox.hasClass("mCS-mouse-over")){functions.hideScrollbar.call(mCSB_scrollTools);}}
							}
						});
					}
					if($this.data("mCS_Init")){$this.data({"mCS_Init":false});}
				}
			}
			/*callbacks*/
			function callbacks(cb){
				this.mcs={
					top:mCSB_container.position().top,left:mCSB_container.position().left,
					draggerTop:mCSB_dragger.position().top,draggerLeft:mCSB_dragger.position().left,
					topPct:Math.round((100*Math.abs(mCSB_container.position().top))/Math.abs(mCSB_container.outerHeight()-mCustomScrollBox.height())),
					leftPct:Math.round((100*Math.abs(mCSB_container.position().left))/Math.abs(mCSB_container.outerWidth()-mCustomScrollBox.width()))
				};
				switch(cb){
					/*start scrolling callback*/
					case "onScrollStart":
						$this.data("mCS_tweenRunning",true).data("onScrollStart_Callback").call($this,this.mcs);
						break;
					case "whileScrolling":
						$this.data("whileScrolling_Callback").call($this,this.mcs);
						break;
					case "onScroll":
						$this.data("onScroll_Callback").call($this,this.mcs);
						break;
					case "onTotalScrollBack":
						$this.data("onTotalScrollBack_Callback").call($this,this.mcs);
						break;
					case "onTotalScroll":
						$this.data("onTotalScroll_Callback").call($this,this.mcs);
						break;
				}
			}
		},
		stop:function(){
			var $this=$(this),
				mCSB_container=$this.children().children(".mCSB_container"),
				mCSB_dragger=$this.children().children().children().children(".mCSB_dragger");
			functions.mTweenAxisStop.call(this,mCSB_container[0]);
			functions.mTweenAxisStop.call(this,mCSB_dragger[0]);
		},
		disable:function(resetScroll){
			var $this=$(this),
				mCustomScrollBox=$this.children(".mCustomScrollBox"),
				mCSB_container=mCustomScrollBox.children(".mCSB_container"),
				mCSB_scrollTools=mCustomScrollBox.children(".mCSB_scrollTools"),
				mCSB_dragger=mCSB_scrollTools.children().children(".mCSB_dragger");
			mCustomScrollBox.unbind("mousewheel focusin mouseenter mouseleave touchend");
			mCSB_container.unbind("touchstart touchmove")
			if(resetScroll){
				if($this.data("horizontalScroll")){
					mCSB_dragger.add(mCSB_container).css("left",0);
				}else{
					mCSB_dragger.add(mCSB_container).css("top",0);
				}
			}
			mCSB_scrollTools.css("display","none");
			mCSB_container.addClass("mCS_no_scrollbar");
			$this.data({"bindEvent_mousewheel":false,"bindEvent_focusin":false,"bindEvent_content_touch":false,"bindEvent_autoHideScrollbar":false}).addClass("mCS_disabled");
		},
		destroy:function(){
			var $this=$(this);
			$this.removeClass("mCustomScrollbar _mCS_"+$this.data("mCustomScrollbarIndex")).addClass("mCS_destroyed").children().children(".mCSB_container").unwrap().children().unwrap().siblings(".mCSB_scrollTools").remove();
			$(document).unbind("mousemove."+$this.data("mCustomScrollbarIndex")+" mouseup."+$this.data("mCustomScrollbarIndex")+" MSPointerMove."+$this.data("mCustomScrollbarIndex")+" MSPointerUp."+$this.data("mCustomScrollbarIndex"));
			$(window).unbind("resize."+$this.data("mCustomScrollbarIndex"));
		}
	},
	functions={
		/*hide/show scrollbar*/
		showScrollbar:function(){
			this.stop().animate({opacity:1},"fast");
		},
		hideScrollbar:function(){
			this.stop().animate({opacity:0},"fast");
		},
		/*js animation tween*/
		mTweenAxis:function(el,prop,to,duration,easing,callbacks){
			var callbacks=callbacks || {},
				onStart=callbacks.onStart || function(){},onUpdate=callbacks.onUpdate || function(){},onComplete=callbacks.onComplete || function(){};
			var startTime=_getTime(),_delay,progress=0,from=el.offsetTop,elStyle=el.style;
			if(prop==="left"){from=el.offsetLeft;}
			var diff=to-from;
			_cancelTween();
			_startTween();
			function _getTime(){
				if(window.performance && window.performance.now){
					return window.performance.now();
				}else{
					if(window.performance && window.performance.webkitNow){
						return window.performance.webkitNow();
					}else{
						if(Date.now){return Date.now();}else{return new Date().getTime();}
					}
				}
			}
			function _step(){
				if(!progress){onStart.call();}
				progress=_getTime()-startTime;
				_tween();
				if(progress>=el._time){
					el._time=(progress>el._time) ? progress+_delay-(progress- el._time) : progress+_delay-1;
					if(el._time<progress+1){el._time=progress+1;}
				}
				if(el._time<duration){el._id=_request(_step);}else{onComplete.call();}
			}
			function _tween(){
				if(duration>0){
					el.currVal=_ease(el._time,from,diff,duration,easing);
					elStyle[prop]=Math.round(el.currVal)+"px";
				}else{
					elStyle[prop]=to+"px";
				}
				onUpdate.call();
			}
			function _startTween(){
				_delay=1000/60;
				el._time=progress+_delay;
				_request=(!window.requestAnimationFrame) ? function(f){_tween(); return setTimeout(f,0.01);} : window.requestAnimationFrame;
				el._id=_request(_step);
			}
			function _cancelTween(){
				if(el._id==null){return;}
				if(!window.requestAnimationFrame){clearTimeout(el._id);
				}else{window.cancelAnimationFrame(el._id);}
				el._id=null;
			}
			function _ease(t,b,c,d,type){
				switch(type){
					case "linear":
						return c*t/d + b;
						break;
					case "easeOutQuad":
						t /= d; return -c * t*(t-2) + b;
						break;
					case "easeInOutQuad":
						t /= d/2;
						if (t < 1) return c/2*t*t + b;
						t--;
						return -c/2 * (t*(t-2) - 1) + b;
						break;
					case "easeOutCubic":
						t /= d; t--; return c*(t*t*t + 1) + b;
						break;
					case "easeOutQuart":
						t /= d; t--; return -c * (t*t*t*t - 1) + b;
						break;
					case "easeOutQuint":
						t /= d; t--; return c*(t*t*t*t*t + 1) + b;
						break;
					case "easeOutCirc":
						t /= d; t--; return c * Math.sqrt(1 - t*t) + b;
						break;
					case "easeOutSine":
						return c * Math.sin(t/d * (Math.PI/2)) + b;
						break;
					case "easeOutExpo":
						return c * ( -Math.pow( 2, -10 * t/d ) + 1 ) + b;
						break;
					case "mcsEaseOut":
						var ts=(t/=d)*t,tc=ts*t;
						return b+c*(0.499999999999997*tc*ts + -2.5*ts*ts + 5.5*tc + -6.5*ts + 4*t);
						break;
					case "draggerRailEase":
						t /= d/2;
						if (t < 1) return c/2*t*t*t + b;
						t -= 2;
						return c/2*(t*t*t + 2) + b;
						break;
				}
			}
		},
		/*stop js animation tweens*/
		mTweenAxisStop:function(el){
			if(el._id==null){return;}
			if(!window.requestAnimationFrame){clearTimeout(el._id);
			}else{window.cancelAnimationFrame(el._id);}
			el._id=null;
		},
		/*detect requestAnimationFrame and polyfill*/
		rafPolyfill:function(){
			var pfx=["ms","moz","webkit","o"],i=pfx.length;
			while(--i > -1 && !window.requestAnimationFrame){
				window.requestAnimationFrame=window[pfx[i]+"RequestAnimationFrame"];
				window.cancelAnimationFrame=window[pfx[i]+"CancelAnimationFrame"] || window[pfx[i]+"CancelRequestAnimationFrame"];
			}
		}
	}
	/*detect features*/
	functions.rafPolyfill.call(); /*requestAnimationFrame*/
	$.support.touch=!!('ontouchstart' in window); /*touch*/
	$.support.msPointer=window.navigator.msPointerEnabled; /*MSPointer support*/
	/*plugin dependencies*/
	var _dlp=("https:"==document.location.protocol) ? "https:" : "http:";
	$.event.special.mousewheel;/* || document.write('<script src="'+_dlp+'//cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.0.6/jquery.mousewheel.min.js"><\/script>')*/
	/*plugin fn*/
	$.fn.mCustomScrollbar=function(method){
		if(methods[method]){
			return methods[method].apply(this,Array.prototype.slice.call(arguments,1));
		}else if(typeof method==="object" || !method){
			return methods.init.apply(this,arguments);
		}else{
			$.error("Method "+method+" does not exist");
		}
	};
	// End of jquery customer scroll
	
})(this);
